Classes and Objects in Java. What Is an Object?. An object is a software bundle of related state and behavior. Software objects are often used to model.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
BITS Pilani Avinash Gautam Department of Computer Science and Information Systems.
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
1 Object-Oriented Programming Concepts. 2 Recap from last lecture Variables and types –int count Assignments –count = 55 Arithmetic expressions –result.
OBJECT-ORIENTED PROGRAMMING CONCEPTS (Review). What is an Object? What is an Object? Objects have states and behaviors. Example: A dog has states - color,
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
What is an object? Your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior;
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object-oriented Programming Concepts
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Object Oriented Paradigm Programming Paradigms En Mohd Norafizal A.Aziz.
INTRODUCTION TO JAVA PROGRAMMING Chapter 1. What is Computer Programming?
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
CSC241: Object Oriented Programming
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Object-Oriented Programming Concepts
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
______________________________________________________________________________________ SCHOOL OF INTERACTIVE ARTS + TECHNOLOGY [SIAT] |
Chapter 4 Objects and Classes.
Introduction to Object-oriented programming and software development Lecture 1.
Object Oriented Programming Concepts Fatih University Ceng-104-A Introduction to Object Oriented Programming Harun Reşit Zafer This is a slide version.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Design: Identifying Objects
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
The Java Programming Language
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Programming Concepts. Object ► An object is a software bundle of related state and behavior. ► Software objects are often used to model.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Working With Objects Tonga Institute of Higher Education.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Classes, Interfaces and Packages
What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar.
Lesson 1 1 LESSON 1 l Background information l Introduction to Java Introduction and a Taste of Java.
A Java program consists of a set of class definitions, optionally grouped into packages. Each class encapsulates state and behavior appropriate to whatever.
By : Robert Apeldorn. What is OOP?  Object-oriented programming is a programming paradigm that uses “objects” to design applications and computer programs.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Variables Variables:-
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Object and Classes อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 3.
Object Oriented Paradigm OOP’s. Problems with Structured Programming As programs grow ever larger and more complex, even the structured programming approach.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
DR. NERMIN HAMZA Java: Lecture 2 Java life cycle 2 Java programs normally undergo four phases  Edit  Programmer writes program (and stores program.
Systems Analysis & Programming 10.1 Systems Development 10.2 Programming: A Five-Step Procedure Generations of Programming Languages 10.4 Programming.
Introduction to Object-oriented Programming
What is an Object Objects are key to understanding object-oriented technology. An object can be considered a "thing" that can perform a set of related.
University of Central Florida COP 3330 Object Oriented Programming
Classes and OOP.
Yanal Alahmad Java Workshop Yanal Alahmad
University of Central Florida COP 3330 Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
03/10/14 Chapter 9 Inheritance.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Pemrograman Dasar Methods PTIIK - UB.
Object Oriented Programming in java
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Classes and Objects in Java

What Is an Object?. An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

Objects Objects are key to understanding object-oriented technology. In the world around you, you'll find many examples of real-world objects: your dog, your desk, your television set, your Square. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Squares also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Exercise Consider the elements of a Dog object in terms of static attributes and methods

Software Objects Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object- oriented programming

Advantages of Software Objects Bundling code into individual software objects provides a number of benefits, including: Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine

What Is a Class? A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

Instantiation In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other Squares in existence, all of the same make and model. Each Square was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your Square is an instance of the class of objects known as Squares. A class is the blueprint from which individual objects are created.

classes are defined in the following way: class MyClass { //field, constructor, and method declarations }

class declaration The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.

Example of a class declaration public class Square { // the Square class has two fields public int side; public String colour; // the Square class has one constructor public Square(int startside, String startcolour) { side = startside; colour = startcolour; } // the Square class has three methods public void changecolour(String newcolour) { colour = newcolour; } public void decreasesize(int decrement) { side -= decrement; } public void increasesize(int increment) { side += increment; } }

Exercise Create a circle class which has 1 constructor and 1 method to output circle area.

Components of Class Declarations. In general, class declarations can include these components, in order: Modifiers such as public, private, and a number of others that you will encounter later. The class name, with the initial letter capitalized by convention. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. The class body, surrounded by braces, {}.

Note Interfaces An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it

What Is an Interface? Objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; The buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. In its most common form, an interface is a group of related methods with empty bodies.

Declaring Member Variables There are several kinds of variables: Member variables in a class—these are called fields. Variables in a method or block of code— these are called local variables. Variables in method declarations—these are called parameters.

Example Field public int side; public String colour;

Example Local Variable public void decreasesizebyfive() { int decrementa = 5; side -= decrementa; } int decrementa = 5; is the local Variable Declaration within the body of a method

Variables in method declarations— these are called parameters. public void changecolour(String newcolour) { colour = newcolour; } String newcolour is a parameter declaration

Field declarations Example public int gear; public int speed; Field declarations are composed of three components, in order: Zero or more modifiers, such as public or private. The field's type e.g. int float etc The field's name. e.g. gear

Types All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you can use reference types, such as strings, arrays, or objects.

Variable Naming Conventions Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

Subsequent Characters Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

The Name The name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Public and Private Access Modifiers Access Modifiers The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. public modifier—the field is accessible from all classes. private modifier—the field is accessible only within its own class. In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from within the class. If we still need access to these values, however, then this can be done indirectly by adding public methods that obtain the field values for us:

Public Public Components for example Steering Wheel, Door Handles etc Not worried about Sparkplugs Electrics Etc Private Components

Consider the following Class (from Java Documentation) public class Bicycle { private int cadence; private int gear; private int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public int getCadence() { return cadence; } public void setCadence(int newValue) { cadence = newValue; } public int getGear() { return gear; } public void setGear(int newValue) { gear = newValue; } public int getSpeed() { return speed; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } }

In this example We see Private Variables Typically they are only accessed from within class However they are retrieved by public methods

Method Declarations method declarations have six components, in order: Modifiers—such as public, private, and others you will learn about later. The return type—the data type of the value returned by the method, or void if the method does not return a value. The method name—the rules for field names apply to method names as well, but the convention is a little different. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. An exception list—to be discussed later. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

Example public int getCadence() { return cadence; } Modifier Public Return type is int Method name is getCadence no parameters, you must use empty parentheses (). Method body enclosed in {} is return cadence;

Another Example public void setCadence(int newValue) { cadence = newValue; } Modifier public Return type void Name setCadence Parameter int newValue Body cadence = newValue;

When Designing a Class The following steps should be followed Identify field attributes and their associated types Write the constructor method Identify operations necessary to change the data in the class. Implement each operation by adding a public method to make the change Identify observer methods that can be used to return information about the attributes in the class. Write a display method that writes data to the screen, if required.

Exercise Write and implement a class called date which represents a calendar date.

Further exercises Add methods to your class which 1) print out a given date in the form e.g. “Today is the 5 th day of January, 2008” for the data d = 5, m=1,y=2008 2) A method which prints out the successor date for a given date