1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to...

100
1 Chapter 2 Objects and Classes

Transcript of 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to...

Page 1: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

1

Chapter 2

Objects and Classes

Page 2: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

2

Objectives To understand objects and classes and use classes to model objects. To learn how to declare a class and how to create an object of a class. To understand the roles of constructors and use constructors to create objects. To use UML graphical notations to describe classes and objects. To distinguish between object reference variables and primitive data type

variables. To use classes in the Java library. To declare private data fields with appropriate get and set methods to make class

easy to maintain. To develop methods with object arguments. To understand the difference between instance and static variables and methods. To determine the scope of variables in the context of a class. To use the keyword this as the reference to the current object that invokes the

instance method. To store and process objects in arrays. To apply class abstraction to develop software. To declare inner classes.

Page 3: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

3

OO Programming ConceptsObjects

Object-oriented programming (OOP) involves programming using objects.

An object represents or an abstraction of some entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a

button, a cow, a car, a loan, and etc. An object may be physical, like a radio, or

intangible, like a song. Just as a noun is a person, place, or thing; so is

an object

Page 4: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

4

OO Programming Concepts An object has a unique identity

State or characteristics or attributes, and Action or behaviors.

Specifically, an object is an entity that consists of: a set of data fields (also known as properties

or attributes) with their current values. A set of methods that use or manipulate the

data ( the behaviors).

Page 5: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

5

Objects – Example 1

An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Class Name: Circle Data Fields:

radius is _______ Methods:

getArea

Circle Object 1 Data Fields:

radius is 10

Circle Object 2 Data Fields:

radius is 25

Circle Object 3 Data Fields:

radius is 125

A class template

Three objects of the Circle class

Page 6: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Objects – Example 2

A remote control unit is an object. A remote control object has three attributes:

– the current channel, an integer,– the volume level, an integer, and – the current state of the TV, on or off, true or false,

Along with five behaviors or methods:– raise the volume by one unit, – lower the volume by one unit, – increase the channel number by one, – decrease the channel number by one, and – switch the TV on or off.

Page 7: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Objects – Example 2 (Cont.)

Three different remote objects, each with unique attribute values (data) but all sharing the

same methods or behaviors.

Page 8: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Objects – Example 2 (Cont.)

The remote control unit exemplifies encapsulation. Encapsulation is defined as the language feature

of packaging attributes and behaviors into a single unit.

Data and methods comprise a single entity. Each remote control object encapsulates data and

methods, attributes and behaviors. An individual remote unit, an object, stores its

own attributes – channel number, volume level, power state – and has the functionality to change those attributes.

Page 9: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Objects – Example 3

A rectangle is an object.

The attributes of a rectangle might be length and width, two floating point numbers; the methods compute and return area and perimeter.

Each rectangle has its own set of attributes; all share the same behaviors

Page 10: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Three rectangle objects

Objects – Example 3 (Cont.)

Page 11: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Three String Objects A character string is an object that encapsulates

data and methods. The string data consists of an ordered sequence of

characters and two (of many) methods include a method that returns the number of characters in the String and one that returns the ith character

Objects – Example 4

Page 12: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

12

Classes

Class is a template or blueprint, from which objects of the same type are created.

A Java class uses variables to define data fields and methods to define behaviors.

Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

Page 13: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

13

Unified Modelling Language (UML) Class Diagram

Circle

radius: double Circle()

Circle(newRadius: double)

getArea(): double

circle1: Circle radius: 10

Class name

Data fields

Constructors and Methods

circle2: Circle radius: 25

circle3: Circle radius: 125

UML Class Diagram

UML notation for objects

Page 14: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

14

Classes class Circle {

/** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; }

}

Data field

Method

Constructors

Page 15: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Classes – Exercise 1

Rectangle Class

A Rectangle class might specify that every Rectangle object consists of two variables of type double:

– double length, and – double width,

Every Rectangle object comes equipped with two methods:– double area(), and //returns the area, length x width, – double perimeter(), //returns the perimeter, 2(length + width).

Individual Rectangle objects may differ in dimension but all Rectangle objects share the same methods

Question:• Draw a UML class diagram of rectangle class• Create a rectangle class

Page 16: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

16

Constructors

Circle() {}

Circle(double newRadius) { radius = newRadius;}

Constructors are a special kind of methods that are invoked to construct objects.

Page 17: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

17

Constructors (Cont.) A constructor with no parameters is referred to as

a no-arg constructor. Constructors must have the same name as the class

itself. Constructors do not have a return type—not even

void. Constructors are invoked using the new operator

when an object is created. Constructors play the role of initializing objects.

Page 18: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

18

Creating Objects Using Constructors

Syntax:

new ClassName();

Example:

new Circle();new Circle(5.0);

Page 19: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

19

Default Constructor

A class may be declared without constructors. In this case, a no-arg constructor with an empty

body is implicitly declared in the class. This constructor, called a default constructor, is

provided automatically only if no constructors are explicitly declared in the class.

Page 20: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

20

Declaring Object Reference Variables

To reference an object, assign the object to a reference variable.

To declare a reference variable, use the syntax:ClassName objectRefVar;

Example:Circle myCircle;

Page 21: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

21

Declaring/Creating Objectsin a Single Step

ClassName objectRefVar = new ClassName();

Example:Circle myCircle = new Circle();

Create an objectAssign object reference

Page 22: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

22

Accessing Objects Data field can be accessed and its methods invoked

using the dot operator (.) – known as object member access operator.

Referencing the object’s data: objectRefVar.data e.g., myCircle.radius

Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

Page 23: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

23

A Simple Circle Class

Objective: Demonstrate creating objects, accessing data, and using methods.

TestCircle1TestCircle1 RunRun

Page 24: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

24

Trace Code

Circle myCircle = new Circle(5.0);

SCircle yourCircle = new Circle();

yourCircle.radius = 100;

Declare myCircle

no valuemyCircle

animation

Page 25: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

25

Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

no valuemyCircle

Create a circle

animation

Page 26: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

26

Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

reference valuemyCircle

Assign object reference to myCircle

animation

Page 27: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

27

Trace Code, cont.Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

reference valuemyCircle

no valueyourCircle

Declare yourCircle

animation

Page 28: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

28

Trace Code, cont.Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

reference valuemyCircle

no valueyourCircle

: Circle radius: 0.0

Create a new Circle object

animation

Page 29: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

29

Trace Code, cont.Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

reference valuemyCircle

reference valueyourCircle

: Circle radius: 1.0

Assign object reference to yourCircle

animation

Page 30: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

30

Trace Code, cont.Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle radius: 5.0

reference valuemyCircle

reference valueyourCircle

: Circle radius: 100.0

Change radius in

yourCircle

animation

Page 31: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

31

1. public class TestCircle1 {2. public static void main(String[] args) {3. Circle1 myCircle = new Circle1(5.0);4. System.out.println(“The area of the circle of radius “ +5. myCircle.radius + “ is “ +6. myCircle.getArea());7. Circle1 yourCircle = new Circle1();8. System.out.println(“The area of the circle of radius “ + 9. yourCircle.radius + “ is “ + 10. yourCircle.getArea()); 11. yourCircle.radius = 100;12. System.out.println(“The area of the circle of radius “ + 13. yourCircle.radius + “ is “ + 14. yourCircle.getArea());15. }16. }

Page 32: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

32

17. class Circle1 {

18. double radius;

19. Circle1( ) {

20. radius = 1.0;

21. }

22. Circle1(double newRadius) {

23. radius = newRadius;

24. }

25. double getArea( ) {

26. return radius * radius * radius *

27. Math.PI;

28. }

29. }

Page 33: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

33

CautionRecall that you use

Math.methodName(arguments) (e.g., Math.pow(3, 2.5))

to invoke a method in the Math class. Can you invoke getArea() using Circle1.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using

objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).

More explanations will be given in Section 2.7, “Static Variables, Constants, and Methods.”

Page 34: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

34

Reference Data FieldsThe data fields can be of reference types. For example, the following Student class contains a data field name of the String type.

public class Student {

String name; // name has default value null

int age; // age has default value 0

boolean isScienceMajor; // isScienceMajor has default value false

char gender; // c has default value '\u0000'

}

Page 35: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

35

The null Value

If a data field of a reference type does not reference any object, the data field holds a special literal value, null.

Page 36: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

36

Default Value for a Data FieldThe default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test {

public static void main(String[] args) {

Student student = new Student();

System.out.println("name? " + student.name);

System.out.println("age? " + student.age);

System.out.println("isScienceMajor? " + student.isScienceMajor);

System.out.println("gender? " + student.gender);

}

}

Page 37: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

37

Example

public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); }}

Compilation error: variables not initialized

Java assigns no default value to a local variable inside a method.

Page 38: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

38

1. public class TestCircle1 {2. public static void main(String[] args) {3. double localVar;4. //Circle1 myCircle = new Circle1(5.0);5. //System.out.println(“The area of the circle of radius “ +6. myCircle.radius + “ is “ +7. myCircle.getArea());8. Circle1 yourCircle = new Circle1();9. System.out.println(“The default value for radius is “ + 10. yourCircle.radius); 11. System.out.println(“Default value for local variable is “ + 12. localVar);13. // yourCircle.radius = 100;14. //System.out.println(“The area of the circle of radius “ + 15. yourCircle.radius + “ is “ + 16. yourCircle.getArea());17. }18. }

Page 39: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

39

17. class Circle1 {

18. double radius;

19. Circle1( ) {

20. // radius = 1.0;

21. }

22. Circle1(double newRadius) {

23. radius = newRadius;

24. }

25. double getArea( ) {

26. return radius * radius * radius *

27. Math.PI;

28. }

29. }

Page 40: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

40

Differences between Variables of Primitive Data Types and Object Types

1 Primitive type int i = 1 i

Object type Circle c c reference

Created using new Circle()

c: Circle

radius = 1

Page 41: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

41

Copying Variables of Primitive Data Types and Object Types

i

Primitive type assignment i = j

Before:

1

j

2

i

After:

2

j

2

c1

Object type assignment c1 = c2

Before:

c2

c1

After:

c2

c1: Circle

radius = 5

C2: Circle

radius = 9

c1: Circle

radius = 5

C2: Circle

radius = 9

Page 42: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

42

Garbage Collection

As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. This clean-up process is called garbage collectionGarbage is automatically collected by Java Virtual Machine (JVM).

Page 43: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

43

Garbage Collection, cont

TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.

Page 44: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

44

Garbage Collection, cont If an object remains referenced but is no longer used in a program, the garbage collector does not recycle

the memory:

Square mySquare = new Square (5.0); // a 5.0 x 5.0 squaredouble areaSquare = mySquare.area();

Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); // a circle of radius 4.0double areaCircle = myCirclearea();…// code that uses these objects…// more code that does not use the objects created above

...

When Square, Triangle and Circle objects are no longer used by the program, if the objects remain referenced, that is, if references mySquare, myTriangle, and myCircle continue to hold the addresses of these obsolete objects, the garbage collector will not reclaim the memory for these three objects.

Such a scenario causes a memory leak.

Page 45: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

45

Garbage Collection, cont A memory leak occurs when an application fails to release or recycle memory that is no longer needed. The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a few

lines of code :

Square mySquare = new Square (5.0); // a 5.0 x 5.0 squaredouble areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); // a circle of radius 4.0double areaCircle = myCircle.area() // code that uses these objects…mySquare = null; myTriangle = null;myCircle = null; // more code that does not use the objects created above

... 

The Java constant null can be assigned to a reference. A reference with value null refers to no object and holds no address; it is called a void reference.

Page 46: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

46

Garbage Collection, cont

Referenced and unreferenced objects

Page 47: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

47

Exercise 1 Develop an Object Oriented program to display the

balance of your account after each transaction. The program must has a class named Account with two type of constructors. – A no-arg constructor that creates a default balance with value is 100.00.– A constructor that update the balance based on the specified transaction,

which are either withdrawal or deposit.– A method named getBalance() that returns the balance of the account.

Use data field balance to hold the current balance of the account. Assign and display no transaction, transaction value is 200.00 and transaction value is –50.00 when you create the objects.

Page 48: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

48

Exercise 2 Write an Object Oriented program to display area and

perimeter of a rectangle. Design a class named Rectangle to represent the rectangle and the class contains:– Two double data fields named width and height that specify the

width and height of the rectangle. The default values are 1 for both width and height

– A no-arg constructor that creates a default rectangle.– A constructor that creates a rectangle with the specified width

and height.– A method named getArea() that returns the area of this rectangle.– A method named getPerimeter() that returns the perimeter.

Assign width 4 and height 40 for the first object and width 3.5 and height 35.9 to the second object.

Page 49: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

49

Using Classes from the Java Library

Example 2.1 declared the Circle1 class and created objects from the class. Often you will use the classes in the Java library to develop programs. You learned to obtain the current time using System.currentTimeMillis() in previous chapter (Primitive Data Types and Operations), “Displaying Current Time.” You used the division and remainder operators to extract current second, minute, and hour.

Page 50: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

50

The Date ClassJava provides a system-independent encapsulation of date and time in the java.util.Date class. Date class can be used to create an instance for the current date and time

To return the date and time as a string its toString method is used.

java.util.Date

+Date()

+Date(elapseTime: long)

+toString(): String

+getTime(): long

+setTime(elapseTime: long): void

Constructs a Date object for the current time.

Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT.

Returns a string representing the date and time.

Returns the number of milliseconds since January 1, 1970, GMT.

Sets a new elapse time in the object.

The + sign indicates public modifer

Page 51: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

51

The Date Class ExampleFor example, the following code

java.util.Date date = new java.util.Date();

System.out.println(date.toString());

displays a string like Mon Jul 20 12:55:57 MYT 2009

Page 52: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

52

The Random ClassYou have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.

java.util.Random

+Random()

+Random(seed: long)

+nextInt(): int

+nextInt(n: int): int

+nextLong(): long

+nextDouble(): double

+nextFloat(): float

+nextBoolean(): boolean

Constructs a Random object with the current time as its seed.

Constructs a Random object with a specified seed.

Returns a random int value.

Returns a random int value between 0 and n (exclusive).

Returns a random long value.

Returns a random double value between 0.0 and 1.0 (exclusive).

Returns a random float value between 0.0F and 1.0F (exclusive).

Returns a random boolean value.

Page 53: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

53

The Random Class ExampleIf two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3.

Random random1 = new Random(3);

System.out.print("From random1: ");

for (int i = 0; i < 10; i++)

System.out.print(random1.nextInt(1000) + " ");

Random random2 = new Random(3);

System.out.print("\nFrom random2: ");

for (int i = 0; i < 10; i++)

System.out.print(random2.nextInt(1000) + " ");

From random1: 734 660 210 581 128 202 549 564 459 961

From random2: 734 660 210 581 128 202 549 564 459 961

Page 54: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

54

Instance Variables, and Methods

Instance variables belong to a specific instance.•There is a separate copy for every object created.

Instance methods are invoked by an instance of the class.

Page 55: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

55

Static Variables, Constants, and Methods

Static variables are shared by all the instances of the class.• only exists one copy no matter how many

objects create• For example, to hold the grand total of

anything

Static methods are not tied to a specific object.

Static constants are final variables shared by all the instances of the class.

Page 56: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

56

Static Variables, Constants, and Methods, cont.

To declare static variables, constants, and methods, use the static modifier.

Keyword static denote a class variable

Page 57: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

57

17. class Circle2 {18. double radius;19. static int numberOfObjects = 0; // Class variable20. 21. Circle2( ) {22. radius = 1.0;23. numberOfObjects++; }24. 25. Circle2(double newRadius) {26. radius = newRadius;27. numberOfObjects++; }28. 29. double getArea( ) {30. return radius * radius * Math.PI; }31. 32. static int getNumberOfObjects() {33. return numberOfObjects; }34. }

Page 58: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

58

Static Variables, Constants, and Methods, cont.

Circle radius: double numberOfObjects: int getNumberOfObjects(): int +getArea(): double

1 radius

circle1 radius = 1 numberOfObjects = 2

instantiate

instantiate

Memory

2

5 radius

numberOfObjects

UML Notation: underline: static variables or methods

circle2 radius = 5 numberOfObjects = 2

Circle2 circle1 = new Circle2();Circle2 circle2 = new Circle2(5);

Page 59: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

59

Static Variables, Constants, and Methods, cont.

circle1.numberOfObjects and circle1.getNumberOfobjects() can be replaced with Circle1.numberOfObjects and Circle2.getNumberOfObjects().

Syntax: ClassName.methodName(arguments) to invoke a static methodClassName.staticVariable.

This improves readability because the user can easily recognise the static method and data in the class.

Page 60: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

60

Static Variables, Constants, and Methods, cont.

Instance variables and methods can only be used from instance method, not from static methods, since static variables and methods belong to the class as a whole and not to particular objects.

Example: static int getNumberOfObjects() {

radius = radius * radius;return numberOfObjects;

}

* wrong because radius is instance variable, not static variable and cannot be used in static method.

Page 61: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

61

Visibility Modifiers and Accessor/Mutator Methods

By default, the class, variable, or method can beaccessed by any class in the same package.

publicThe class, data, or method is visible to any class in any package.

private The data or methods can be accessed only by the declaring class.

The get and set methods are used to read and modify private properties.

Page 62: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

62

The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.

public class C1 { public int x; int y; private int z; public void m1() { } void m2() { } private void m3() { } }

public class C2 { void aMethod() { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; can invoke o.m1(); can invoke o.m2();

cannot invoke o.m3(); } }

package p1; package p2;

public class C3 { void aMethod() { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); } }

class C1 { ... }

public class C2 { can access C1 }

package p1; package p2;

public class C3 { cannot access C1; can access C2; }

Page 63: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

63

NOTE

An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as

shown in (a). public class Foo { private boolean x; public static void main(String[] args) {

Foo foo = new Foo(); System.out.println(foo.x);

System.out.println(foo.convert()); } private int convert(boolean b) { return x ? 1 : -1; } }

(a) This is OK because object foo is used inside the Foo class

public class Test { public static void main(String[] args) { Foo foo = new Foo(); System.out.println(foo.x); System.out.println(foo.convert(foo.x)); } }

(b) This is wrong because x and convert are private in Foo.

Page 64: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

64

Why Data Fields Should Be private?

To protect data.

To make class easy to maintain.

Page 65: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

65

Why Data Fields Should Be private?

Example: data field radius and numberOfObjects in the Circle2 class can be modified directly (e.g. myCircle.radius = 5).

This is not a good practice:– Data may be tampered. For example, numberOfObjects is to

count the number of objects created, but it may be set to an arbitrary value (e.g. Circle2.numberOfObjects = 10).

– It makes the class difficult to maintain and vulnerable to bugs.Suppose you want to modify the Circle2 class to ensure that the radius is non-negative after other programs have already used the class. You have to change not only the Circle2 class, but also the programs that use the Circle2 class.

Page 66: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

66

Why Data Fields Should Be private?

Data field encapsulation: declare the data field as private to prevent direct modification of properties

Provide a get method to return the value of the data field. (getter/accessor)

Provide a set method to enable a private data field to be updated (setter/mutator)

Page 67: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

67

Example ofData Field Encapsulation

Circle3Circle3 RunRunTestCircle3TestCircle3

Circle

-radius: double

-numberOfObjects: int

+Circle()

+Circle(radius: double)

+getRadius(): double

+setRadius(radius: double): void

+getNumberOfObject(): int

+getArea(): double

The radius of this circle (default: 1.0).

The number of circle objects created.

Constructs a default circle object.

Constructs a circle object with the specified radius.

Returns the radius of this circle.

Sets a new radius for this circle.

Returns the number of circle objects created.

Returns the area of this circle.

The - sign indicates private modifier

Page 68: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

68

17. public class Circle3 {18. private double radius = 1;19. private static int numberOfObjects = 0;20. 21. public Circle3( ) {22. numberOfObjects++; }23. 24. public Circle2(double newRadius) {25. radius = newRadius;26. numberOfObjects++; }27. 28. public void setRadius(double newRadius ) {29. radius = (newRadius >= 0) ? newRadius : 0; }30. 31. public static int getNumberOfObjects() {32. return numberOfObjects; }33. 34. public double getArea() {35. return radius * radius * Math.PI36. }37. }

Page 69: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

69

Immutable Objects and ClassesIf the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method.

A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable.

Page 70: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

70

Examplepublic class Student { private int id; private BirthDate birthDate;

public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); }

public int getId() { return id; }

public BirthDate getBirthDate() { return birthDate; }}

public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; }}

public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! }}

Page 71: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

71

What Class is Immutable?

For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.

Page 72: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

72

Passing Objects to Methods

Passing by value for primitive type value (the value is passed to the parameter)

Passing by value for reference type value (the value is the reference to the object)

TestPassObjectTestPassObject RunRun

Page 73: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

73

Passing Objects to Methods, cont.

Space required for the main method int n: 5 myCircle:

Stack Space required for the printAreas method int times: 5 Circle c:

reference A circle object

Heap

reference

Pass by value (here the value is the reference for the object)

Pass by value (here the value is 5)

Page 74: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

74

Scope of Variables

The scope of instance and static variables is the entire

class. They can be declared anywhere inside a class.

The scope of a local variable starts from its declaration

and continues to the end of the block that contains the

variable. A local variable must be initialized explicitly

before it can be used.

The exception is when a data field is initialized based on

reference to another data field.

Page 75: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

75

Scope of Variablespublic class Circle { public double find getArea() { return radius * radius * Math.PI; }

private double radius = 1;}

public class Foo { private i; private int j = i + 1;}

Page 76: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

76

Scope of variables

class Foo { int x = 0; int y = 0;

Foo() { }

void p() { int x = 1; System.out.println(“x = “ + x); System.out.println(“y = “ + y); }}

Page 77: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

77

The this Keyword Is a reference to the calling object

Use this:

– to refer to the object that invokes the instance method.

– to refer to an instance data field.

– to invoke an overloaded constructor of the same class.

Page 78: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

78

Serving as Proxy to the Calling Object

class Foo { int i = 5; static double k = 0; void setI(int i) { this.i = i; } static void setK(double k) { Foo.k = k; } }

Suppose that f1 and f2 are two objects of Foo. Invoking f1.setI(10) is to execute f1.i = 10, where this is replaced by f1 Invoking f2.setI(45) is to execute f2.i = 45, where this is replaced by f2

Page 79: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

79

Calling Overloaded Constructor public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public Circle() { this(1.0); } public double getArea() { return this.radius * this.radius * Math.PI; } }

Every instance variable belongs to an instance represented by this, which is normally omitted

this must be explicitly used to reference the data field radius of the object being constructed

this is used to invoke another constructor

Page 80: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

80

Array of Objects Circle[] circleArray = new Circle[10];

An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.

Page 81: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

81

Array of Objects, cont.

reference

Circle object 0 circleArray[0]

circleArray circleArray[1]

circleArray[9]

Circle object 9

Circle object 1

Circle[] circleArray = new Circle[10];

Page 82: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

82

Array of Objects, cont.

Summarizing the areas of the circles

TotalAreaTotalArea RunRun

Page 83: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

83

1. public class TotalArea {2. public static void main(String[] args) {3. Circle3[] circleArray;4. circleArray = createCircleArray();5. printCircleArray(circleArray);6. }7. 8. public static Circle3[] createCircleArray() {9. Circle3[] circleArray = new Circle3[10];10. for (int I = 0; I < circleArray.length; i++) {11. circleArray[i] = new Circle3(Math.random() * 100);12. return circleArray;13. }

Page 84: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

84

13. public static printCircleArray(Circle3[] circleArray) {14. System.out.println (“Radius\t\t\t\t” + “Area”);15. for (int i = 0; i < circleArray.length; i++) {16. System.out.println(circleArray[i].getRadius() + “\t\t” +17. circleArray[i].getArea() + ‘\n’);18. }19. System.out.println(“-----------------”);20. System.out.println(“The total areas of circles is \t” + 21. sum(circleArray);22. }23. 24. public static double sum(Circle3[] circleArray) {25. double sum = 0;26. for (int i = 0; i < circleArray.length; i++)27. sum += circleArray[i].getArea();28. return sum;29. }

Page 85: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

85

Class Abstraction and EncapsulationClass abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

Class Contract (Signatures of

public methods and public constants)

Class

Class implementation is like a black box hidden from the clients

Clients use the

class through the contract of the class

Page 86: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

86

Example: The Loan Class

TestLoanClassTestLoanClass RunRunLoanLoan

Loan

-annualInterestRate: double

-numberOfYears: int

-loanAmount: double

-loanDate: Date

+Loan()

+Loan(annualInterestRate: double, numberOfYears: int, loanAmount: double)

+getAnnualInterestRate(): double

+getNumberOfYears(): int

+getLoanAmount(): double

+getLoanDate(): Date

+setAnnualInterestRate( annualInterestRate: double): void

+setNumberOfYears( numberOfYears: int): void

+setLoanAmount( loanAmount: double): void

+getMonthlyPayment(): double

+getTotalPayment(): double

The annual interest rate of the loan (default: 2.5).

The number of years for the loan (default: 1)

The loan amount (default: 1000).

The date this loan was created.

Constructs a default Loan object.

Constructs a loan with specified interest rate, years, and loan amount.

Returns the annual interest rate of this loan.

Returns the number of the years of this loan.

Returns the amount of this loan.

Returns the date of the creation of this loan.

Sets a new annual interest rate to this loan.

Sets a new number of years to this loan.

Sets a new amount to this loan.

Returns the monthly payment of this loan.

Returns the total payment of this loan.

Page 87: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

87

Example: The Course Class

TestCourceTestCource RunRunCourseCourse

Course

-name: String

-students: String[]

-numberOfStudents: int

+Course(name: String)

+getName(): String

+addStudent(student: String): void

+getStudents(): String[]

+getNumberOfStudents(): int

The name of the course.

The students who take the course.

The number of students (default: 0).

Creates a Course with the specified name.

Returns the course name.

Adds a new student to the course list.

Returns the students for the course.

Returns the number of students for the course.

Page 88: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

88

Example: The StackOfIntegers Class

RunRunTestStackOfIntegersTestStackOfIntegers

StackOfIntegers

-elements: int[]

-size: int

+StackOfIntegers()

+StackOfIntegers(capacity: int)

+empty(): boolean

+peek(): int

+push(value: int): int

+pop(): int

+getSize(): int

An array to store integers in the stack.

The number of integers in the stack.

Constructs an empty stack with a default capacity of 16.

Constructs an empty stack with a specified capacity.

Returns true if the stack is empty.

Returns the integer at the top of the stack without removing it from the stack.

Stores an integer into the top of the stack.

Removes the integer at the top of the stack and returns it.

Returns the number of elements in the stack.

Page 89: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

89

Implementing StackOfIntegers Class

StackOfIntegersStackOfIntegers

.

.

.

. . .

elements[0]

elements[1]

elements[size-1] capacity

top

bottom

size

elements[capacity – 1]

Page 90: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

90

Note to Instructor

You can now cover Chapter 8, “Strings and Text I/O,” or Chapter 12, “GUI Basics.”

Page 91: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

91

Creating Windows Using the JFrame Class

Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames.

TestFrameTestFrame RunRun

OptionalGUI

Page 92: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

92

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

Declare, create, and assign in one

statementreferenceframe1

: JFrametitle: width:height:visible:

animation

Page 93: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

93

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width:height:visible:

Set title property

animation

Page 94: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

94

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible:

Set size property

animation

Page 95: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

95

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible: true

Set visible property

animation

Page 96: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

96

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible: true

Declare, create, and assign in one

statementreferenceframe2

: JFrametitle:width:height:visible:

animation

Page 97: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

97

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible: true

referenceframe2

: JFrametitle: "Window 2"width:height:visible:

Set title property

animation

Page 98: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

98

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible: true

referenceframe2

: JFrametitle: "Window 2"width: 200height: 150visible:

Set size property

animation

Page 99: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

99

Trace CodeJFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true);

referenceframe1

: JFrametitle: "Window 1"width: 200height: 150visible: true

referenceframe2

: JFrametitle: "Window 2"width: 200height: 150visible: true

Set visible property

animation

Page 100: 1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

100

Exercise 3

Write an Object Oriented program that asks a user to enter the distance of a trip in miles, the miles per gallon estimate for the user’s car, and the average cost of a gallon of gas. Calculate and display the number of gallons of gas needed and the estimated cost of the trip.