Professional Documents
Culture Documents
Objects Concepts
Object Concepts
The term object can be used in two ways, in a general sense and a specific sense. In a general sense, it refers to a group of objects.
Examples are people, books, dogs, cars, etc. We use term class to indicate a category of objects.
In
Examples are you yourself, the book you are current reading, the dog you raise, the car you drive, etc. We use term instance to indicate a particular object.
Object is a natural way to represent an entity in the real world Object example: cells Cell is the basic building block of which all living things are composed. Cells are organic packages that combine related information and behavior.
A cells information is stored inside the cell nucleus. A cell can perform different behaviors, such as energy conversion, chemical reactions, and movement.
Software Objects
In Object-Oriented (OO) programming, an object is a package that contains variables: a set of data methods: a collection of procedures
The class is to define a particular type of objects. Each class has variables and methods owned by the type of objects. A variable defines a specific information about the class. A method is an action performed by the class. A class definition is a blueprint for making object instances. Once youve defined a class, you can create any number of unique instances of the class. All the instances of a class share the same characteristics. The only aspects that differ from one instance to another are the values of its variables of a class.
6
Class: Variables:
Object instances
Student id = 03987654 Student Name = Peter Chan Sex = M Methods: Attending lectures Attending tutorials Submitting assignments Taking examinations
Student id = 03232432 Student Name = Ronald Lo Sex = M Methods: Attending lectures Attending tutorials Submitting assignments Taking examinations
Method area()
Method perimeter()
Note that only the class is defined. No actual object instance has been created yet.
rectangle1
rectangle2
We use another Java program to create the object instances and instruct them to work the RectangleUser class in this example.
COMP 232 / Chapter 6 / OOP I
public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle( ); Rectangle rectangle2 = new Rectangle( ); double area;
area = rectangle1. area(); System.out.println("rectangle1 area " + area); area = rectangle2.area(); System.out.println("rectangle2 area " + area);
10
area = rectangle1. area(); System.out.println("rectangle1 area " + area); area = rectangle2.area(); System.out.println("rectangle2 area " + area);
Object Instantiation
Two objects of class Rectangle are created. Referenced by rectangle1 and rectangle2.
11
double
area;
area = rectangle1.area(); System.out.println("rectangle1 area " + area); area = rectangle2.area(); System.out.println("rectangle2 area " + area);
System.out.println()
public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle( ); Rectangle rectangle2 = new Rectangle( ); double area; area = rectangle1. area(); System.out.println ("rectangle1 area " + area); area = rectangle2.area(); System.out.println("rectangle2 area " + area);
System.out.println()
System is a class provided by Java. out is a variable of class System println() prints the given string on the screen.
Object Interactions
14
Constructors
Object Constructor
public class Rectangle { private double length; private double width;
Constructor Rectangle( )
Constructor: Rectangle( )
same name as the class. automatically called when an object is instantiated. used to set up the object instance upon its creation. for example, initializing instance variables.
16
area = rectangle1.calculateArea(); System.out.println("rectangle1 area " + area); area = rectangle2.calculateArea(); System.out.println("rectangle2 area " + area); } }
Object Instantiation
Two objects of class Rectangle are created. Referenced by rectangle1 and rectangle2. new Rectangle() The statement: actually means that the constructor is called.
17
18
19
20
21
Constructor Revisited
public class Rectangle { private double length; private double width;
A constructor is a special method that is called automatically when an object instance of that class is instantiated. Constructors can take arguments but cannot return a value. An important difference between constructors and other methods is that constructors are not allowed to specify a return type (not even void).
22
Constructor Revisited
A no-argument constructor is one which takes no argument, such as public MyClass(); If no constructors are defined for a class, the compiler creates a default constructor that takes no argument (no-argument constructor). If constructors are defined for a class, but none of the public constructors are noargument constructors, and an attempt is made to call a no-argument constructor during object instantiation of that class, a syntax error occurs. That is, a constructor may be called with no arguments only if there is a no-argument constructor defined, or if there are no constructors for the class (the default constructor provided by the compiler is then called). COMP 232 /
Chapter 6 / OOP I
23
Overloading Constructor
public class Rectangle { private double length; private double width;
A no-argument constructor
A constructor can be overloaded (that is, several constructors exists in the same class, but with different signatures).
public Rectangle(double l, double w) { The appropriate constructor length = l; is invoked by matching the width = w; number, types and order of the arguments specified in } the constructor call with ..
public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(); Rectangle rectangle2 = new Rectangle(25.3, 20.4);
24
Access Specifiers
Access Specifiers
public class Rectangle { private double length; private double width; ..
Variables
private
double
length;
Access specifier
private / public / protected Access specifiers are used both for instance variables and methods
public - the class, data, or method is visible to any class. private - the data or methods can be accessed only by the declaring class. protected discuss later
COMP 232 / Chapter 6 / OOP I 26
You dont want your personal (private) properties to be seen, used, or modified by others. Instance variables should private properties of the class. We can use the access specifier private.
length is private
public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(25.3, 20.4);
System.out.println( rectangle1.length );
} }
Getter Methods
In order to access private variables (indirectly), a public getter method is provided. The getter method acts as an interface between the caller and the object internals.
public class Rectangle { private double length; private double width; .. public double getLength() { return length; } public double getWidth() { return width; }
public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(25.3, 20.4);
System.out.println( rectangle1.getLength() );
} }
28
Setter Methods
A public setter method can be used to receive values from the caller and store the values to the relevant instance variables. A setter method can provide data validation capability so that only valid data values are stored in the instance variables.
public class Student { Setter method private int score=0; .. public void setScore( int value ) { if (value >= 0 && value <= 100) // store if only 0-100 score = value; else System.err.println(Invalid value); Protects variable } s c o r e from storing } invalid values. public class Teacher { public static void main(String [] argv) { Student peter = new Student();
peter.setScore(60);
COMP 232 / } Chapter 6 / OOP I
29
private Methods
public class Timer { private int hour; private int minute; private int second; public Timer() { setHour(0); setMinute(0); setSecond(0); } public Timer(int h, int m, int s) { setHour(h); setMinute(m); setSecond(s); } private void setHour(int h) { hour = h; } private void setMinute(int m) { minute = m; } private void setSecond(int s) { second = s; }
30
Another Example
import java.text.DecimalFormat; public class Time0 { private int hour; private int minute; private int second; public Time0() { setTime (0, 0, 0); }
public void setTime(int h, int m, int s) { if (h>=0 && h<=23) hour = h; if (m>=0 && m<=59) minute = m; if (s>=0 && s<=59) second = s; }
public String printTime() { DecimalFormat twoDigits = new DecimalFormat("00"); return twoDigits.format(hour) + ":" + twoDigits.format(minute) + ":" + twoDigits.format(second);
31
import java.io.*; public class Time0Test { public static void main(String [] args) { Time0 t = new Time0(); // initial t System.out.print("Initial time: "); System.out.println(t.printTime()); // set to 13:27:6 System.out.println("Setting to 13:27:6"); t.setTime(13, 27, 6); System.out.println(t.printTime()); // set to 99:99:99, which is invalid System.out.println("Setting to 99:99:99"); t.setTime(99, 99, 99); System.out.println(t.printTime());
32
If you wish, you can put main() and the object definition in one single class.
public Rectangle2(double l, double w) { length = l; width = w; } public double getLength() { return length; } public double getWidth() { return width; } public void setLength(double l) { if (l > 0) length = l; } public void setWidth(double w) { if (w > 0) width = w; }
public static void main(String [] args) { Rectangle2 r = new Rectangle2(3.5, 4.5); } COMP 232 / Chapter 6 / OOP I }
33
End.