Liang Chapter 9
Liang Chapter 9
Chapter 9 Objects and Classes After learning the preceding chapters, you are capable of
solving many programming problems using selections,
loops, methods, and arrays. However, these Java features
are not sufficient for developing graphical user interfaces
and large scale software systems. Suppose you want to
develop a graphical user interface as shown below. How do
CS1: Java Programming you program it?
Colorado State University
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
1 2
rights reserved. rights reserved.
q
To access objects via object reference variables (§9.5).
To define a reference variable using a reference type (§9.5.1).
an entity in the real world that can be distinctly
q To access an object’s data and methods using the object member access operator (.) (§9.5.2). identified. For example, a student, a desk, a circle,
q To define data fields of reference types and assign default values for an object’s data fields (§9.5.3).
q To distinguish between object reference variables and primitive data type variables (§9.5.4). a button, and even a loan can all be viewed as
q
q
To use the Java library classes Date, Random, and Point2D (§9.6).
To distinguish between instance and static variables and methods (§9.7).
objects. An object has a unique identity, state, and
q To define private data fields with appropriate get and set methods (§9.8). behaviors. The state of an object consists of a set of
q To encapsulate data fields to make classes easy to maintain (§9.9).
q To develop methods with object arguments and differentiate between primitive-type arguments and data fields (also known as properties) with their
q
object-type arguments (§9.10).
To store and process objects in arrays (§9.11).
current values. The behavior of an object is defined
q To create immutable objects from immutable classes to protect the contents of objects (§9.12). by a set of methods.
q To determine the scope of variables in the context of a class (§9.13).
q To use the keyword this to refer to the calling object itself (§9.14).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
3 4
rights reserved. rights reserved.
Objects Classes
Class Name: Circle A class template
Data Fields:
radius is _______
Classes are constructs that define objects of the
Methods:
getArea
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Circle Object 1 Circle Object 2 Circle Object 3 Three objects of
the Circle class
Additionally, a class provides a special type of
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is 125 methods, known as constructors, which are invoked
to construct objects from the class.
An object has both a state and behavior. The state
defines the object, and the behavior defines what
the object does.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
5 6
rights reserved. rights reserved.
Classes UML Class Diagram
class Circle { Class name
UML Class Diagram Circle
/** The radius of this circle */
double radius = 1.0; radius: double Data fields
Data field
Circle() Constructors and
/** Construct a circle object */ Circle(newRadius: double) methods
Circle() { getArea(): double
} getPerimeter(): double
Constructors setRadius(newRadius:
double): void
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
} circle2: Circle circle3: Circle UML notation
circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125
/** Return the area of this circle */
double getArea() { Method
return radius * radius * 3.14159;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
7 8
rights reserved. rights reserved.
TV
TestTV Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
9 10
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
13 14
rights reserved. rights reserved.
Example:
Circle myCircle;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
15 16
rights reserved. rights reserved.
animation
yourCircle.radius = 100;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
17 18
rights reserved. rights reserved.
animation animation
Trace Code, cont. Trace Code, cont.
Circle myCircle = new Circle(5.0); myCircle no value Circle myCircle = new Circle(5.0); myCircle reference value
Circle yourCircle = new Circle(); Circle yourCircle = new Circle();
Create a circle
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
19 20
rights reserved. rights reserved.
animation animation
Trace Code, cont. Trace Code, cont.
Circle myCircle = new Circle(5.0); myCircle reference value Circle myCircle = new Circle(5.0); myCircle reference value
Circle yourCircle = new Circle(); Circle yourCircle = new Circle();
: Circle
Declare yourCircle Create a new radius: 1.0
Circle object
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
21 22
rights reserved. rights reserved.
animation animation
Trace Code, cont. Trace Code, cont.
Circle myCircle = new Circle(5.0); myCircle reference value Circle myCircle = new Circle(5.0); myCircle reference value
Circle yourCircle = new Circle(); Circle yourCircle = new Circle();
radius: 1.0
Change radius in radius: 100.0
yourCircle
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
23 24
rights reserved. rights reserved.
Caution Reference Data Fields
Recall that you use The data fields can be of reference types. For example,
Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) the following Student class contains a data field name of
the String type.
to invoke a method in the Math class. Can you invoke getArea() using
SimpleCircle.getArea()? The answer is no. All the methods used before public class Student {
String name; // name has default value null
this chapter are static methods, which are defined using the static int age; // age has default value 0
keyword. However, getArea() is non-static. It must be invoked from an boolean isScienceMajor; // isScienceMajor has default value false
object using char gender; // c has default value '\u0000'
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
25 26
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
27 28
rights reserved. rights reserved.
c1 c1
Garbage is automatically collected by JVM.
c2 c2
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
31 32
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
33 34
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
35 36
rights reserved. rights reserved.
The Random Class Example The Point2D Class
If two Random objects have the same seed, they will generate Java API has a conveninent Point2D class in the
identical sequences of numbers. For example, the following javafx.geometry package for representing a point in a two-
code creates two Random objects with the same seed 3. dimensional plane.
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) + " ");
TestPoint2D Run
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
37 38
rights reserved. rights reserved.
Instance methods are invoked by an instance of Static methods are not tied to a specific object.
the class.
Static constants are final variables shared by all the
Instance variables and methods are specified by instances of the class.
omitting the static keyword.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
39 40
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
41 42
rights reserved. rights reserved.
Example of Visibility Modifiers and
Using Instance and Class Variables Accessor/Mutator Methods
and Method By default, the class, variable, or method can be
accessed by any class in the same package.
Objective: Demonstrate the roles of
q public
instance and class variables and their
The class, data, or method is visible to any class in any
uses. This example adds a class variable package.
numberOfObjects to track the number of
Circle objects created. q private
The data or methods can be accessed only by the declaring
CircleWithStaticMembers class.
TestCircleWithStaticMembers Run The get and set methods are used to read and modify private
properties.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
43 44
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
45 46
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
47 48
rights reserved. rights reserved.
Example of Passing Objects to Methods
Data Field Encapsulation
Circle
q Passing by value for primitive type value
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0). (the value is passed to the parameter)
-numberOfObjects: int The number of circle objects created.
+Circle() Constructs a default circle object. q Passing by value for reference type value
+Circle(radius: double)
+getRadius(): double
Constructs a circle object with the specified radius.
Returns the radius of this circle.
(the value is the reference to the object)
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.
CircleWithPrivateDataFields
TestPassObject Run
TestCircleWithPrivateDataFields Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
49 50
rights reserved. rights reserved.
TotalArea Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
53 54
rights reserved. rights reserved.
Immutable Objects and Classes Example public class BirthDate {
private int year;
public class Student {
private int id;
private int month;
If the contents of an object cannot be changed once the object private BirthDate birthDate;
private int day;
is created, the object is called an immutable object and its class public Student(int ssn,
int year, int month, int day) {
public BirthDate(int newYear,
int newMonth, int newDay) {
is called an immutable class. If you delete the set method in id = ssn;
birthDate = new BirthDate(year, month, day);
year = newYear;
} month = newMonth;
the Circle class in Listing 8.10, the class would be immutable day = newDay;
public int getId() {
because radius is private and cannot be changed without a set return id;
}
}
method. public void setYear(int newYear) {
public BirthDate getBirthDate() { year = newYear;
return birthDate;
}
}
A class with all private data fields and without mutators is not }
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
55 56
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
57 58
rights reserved. rights reserved.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
59 60
rights reserved. rights reserved.
Calling Overloaded Constructor
public class Circle {
private double radius;