Вы находитесь на странице: 1из 34

Chapter 6

Object-Oriented Programming I: Objects and Classes

COMP 232 Fundamentals of Programming

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

a specific sense, it refers to an instance of a category of objects.

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.

COMP 232 / Chapter 6 / OOP I

Object Example - Cells


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.

COMP 232 / Chapter 6 / OOP I

Software Objects

In Object-Oriented (OO) programming, an object is a package that contains variables: a set of data methods: a collection of procedures

COMP 232 / Chapter 6 / OOP I

Class and Instance


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

COMP 232 / Chapter 6 / OOP I

Class: Variables:

Student Student id Student Name Sex

Methods: Attending lectures Attending tutorials Submitting assignments Taking examinations

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

COMP 232 / Chapter 6 / OOP I

Creating and Using Objects

The Rectangle Class


public class Rectangle { private double length; private double width;
Variables

Dont ask me what private and public means right now.

public double area() { return length * width; }


public double perimeter() { return (length + width) * 2; } }

Method area()

Method perimeter()

Note that only the class is defined. No actual object instance has been created yet.

COMP 232 / Chapter 6 / OOP I

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

The RectangleUser Class


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);

Object Instantiation

Two objects of class Rectangle are created. Referenced by rectangle1 and rectangle2.

The syntax for object instantiation: ClassName objectName = new ClassName();


COMP 232 / Chapter 6 / OOP I

11

Calling an Objects Method


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);

Calling the area() Method


Sends a message to rectangle1. Request rectangle1 to perform area(). The method then calculates and returns the area of rectangle1.

COMP 232 / Chapter 6 / OOP I 12

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.

COMP 232 / Chapter 6 / OOP I 13

Object Interactions

COMP 232 / Chapter 6 / OOP I

14

Constructors

Object Constructor
public class Rectangle { private double length; private double width;

public Rectangle( ) { length =0; width = 0; }


public double calculateArea() { return length * 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

COMP 232 / Chapter 6 / OOP I

The RectangleUser Class


public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle( ); Rectangle rectangle2 = new Rectangle( ); double area;

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.

COMP 232 / Chapter 6 / OOP I

17

Object Instantiation with Constructor

COMP 232 / Chapter 6 / OOP I

18

Object Constructor Again


public class Rectangle { private double length; private double width;

public Rectangle(double l, double w) { Constructor length = l; Rectangle() width = w; }


public double calculateArea() { return length * width; }

Constructor: Rectangle(double l, double w)


Constructor is a method, thus can take parameters. The parameters are usually used to initiate instance variables.

COMP 232 / Chapter 6 / OOP I

19

The RectangleUser Class


public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); double area; area = rectangle1.calculateArea(); System.out.println("rectangle1 area " + area); area = rectangle2.calculateArea(); System.out.println("rectangle2 area " + area);

COMP 232 / Chapter 6 / OOP I

20

Object Instantiation with Constructor Parameters

COMP 232 / Chapter 6 / OOP I

21

Constructor Revisited
public class Rectangle { private double length; private double width;

public Rectangle(double l, double w) { length = l; width = w; } .. No return type here

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

COMP 232 / Chapter 6 / OOP I

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

public Rectangle() { length = 0; width = 0; }

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 ..

those defined in the signature.

public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(); Rectangle rectangle2 = new Rectangle(25.3, 20.4);

COMP 232 / Chapter 6 / OOP I

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

private Instance Variables


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.

public class Rectangle { private double length;

private double width;


..

length is private

and cannot be accessed outside the class.

public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(25.3, 20.4);

System.out.println( rectangle1.length );
} }

RectangleUser.java:5: length has private access in Rectangle rectangle1.length ^


COMP 232 / Chapter 6 / OOP I 27

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; }

Getter for length

Getter for width

public class RectangleUser { public static void main(String [] argv) { Rectangle rectangle1 = new Rectangle(25.3, 20.4);

System.out.println( rectangle1.getLength() );
} }

COMP 232 / Chapter 6 / OOP I

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

A private setter method can be used to receive values from constructor

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

COMP 232 / Chapter 6 / OOP I

Another Example
import java.text.DecimalFormat; public class Time0 { private int hour; private int minute; private int second; public Time0() { setTime (0, 0, 0); }

setTime() checks the range of values and protects

the instance variables from storing invalid values.

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

} COMP 232 / Chapter 6 / OOP I

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());

Time has not been changed.

COMP 232 / Chapter 6 / OOP I

32

public class Rectangle2 {


private double length; private double width; public Rectangle2() { length = 0; width = 0; }

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.