CS 112 Programming 2
Lecture 02
Objects and Classes (1)
Chapter 9 Objects and Classes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
2
Objectives
❑ To describe objects and classes, and use classes to model objects (§9.2).
❑ To use UML graphical notation to describe classes and objects (§9.2).
❑ To demonstrate how to define classes and create objects (§9.3).
❑ To create objects using constructors (§9.4).
❑ To access objects via object reference variables (§9.5).
❑ To define a reference variable using a reference type (§9.5.1).
❑ To access an object’s data and methods using the object member access operator (.) (§9.5.2).
❑ To define data fields of reference types and assign default values for an object’s data fields (§9.5.3).
❑ To distinguish between object reference variables and primitive data type variables (§9.5.4).
❑ To use the Java library classes Date, Random, and Point2D (§9.6).
❑ To distinguish between instance and static variables and methods (§9.7).
❑ To define private data fields with appropriate get and set methods (§9.8).
❑ To encapsulate data fields to make classes easy to maintain (§9.9).
❑ To develop methods with object arguments and differentiate between primitive-type arguments and
object-type arguments (§9.10).
❑ To store and process objects in arrays (§9.11).
❑ To create immutable objects from immutable classes to protect the contents of objects (§9.12).
❑ To determine the scope of variables in the context of a class (§9.13).
❑ 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
rights reserved.
3
Object-Oriented Programming
Object-oriented programming (OOP)
involves programming using objects
An object represents an entity in the real world that can
be distinctly identified
Examples: A student, a desk, a circle, and even a loan can
all be viewed as objects
Each object has a unique identity, state, and behaviors:
State of an object consists of a set of data fields (also
known as properties) with their current values
Behavior of an object is defined by a set of methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
Classes
Classes are constructs that
define objects of the same type
▪ 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 that class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
A Java Class
class SimpleCircle {
/** The radius of this circle */
double radius = 1.0; Data field
/** Construct a circle object */
Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** 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
rights reserved.
6
UML Notation for Classes & Objects
UML Class Diagram SimpleCircle Class name
radius: double Data fields
Circle() Constructors and
Circle(newRadius: double) methods
getArea(): double
getPerimeter(): double
setRadius(newRadius:
double): void
circle2: SimpleCircle circle3: SimpleCircle UML notation
circle1: SimpleCircle
for objects
radius = 1.0 radius = 25 radius = 125
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
Example 1: Defining Classes & Creating Objects
Objective: Demonstrate creating objects, accessing data,
and invoking methods of the SimpleCircle class
TestSimpleCircle
Run
TestSimpleCircle Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Constructors
What are They are a special kind of methods that are invoked to
they? construct and initialize objects
How do They must have Circle() {
we define the same name as }
them? the class itself.
They do not have Circle(double newRadius) {
radius = newRadius;
a return type -
}
not even void
How do They are invoked new Circle();
we invoke using the new
new Circle(5.0);
them? operator
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
Default & No-Args Constructors
▪ A constructor without parameters is called a
no-args constructor
Example: Circle() { }
▪ A class may be defined without constructors
▪ In that case, a no-arg constructor with an empty
body is implicitly defined in the class
▪ This constructor, called the default constructor,
is provided automatically only if no
constructors are explicitly defined in the class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
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;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
Declaring & Constructing Objects in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference Create an object
Example:
Circle myCircle = new Circle();
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Accessing Object’s Members
Referencing the object’s data:
objectRefVar.data
Example: myCircle.radius
Invoking the object’s method:
objectRefVar.methodName(arguments)
Example: myCircle.getArea()
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
animation
Trace Code
Declare myCircle
Circle myCircle = new Circle(5.0); no value
myCircle
Circle yourCircle = new Circle();
yourCircle.radius = 100;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); no value
myCircle
Circle yourCircle = new Circle();
yourCircle.radius = 100; : Circle
radius: 5.0
Create a circle
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100; Assign object reference : Circle
to myCircle
radius: 5.0
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100; : Circle
radius: 5.0
yourCircle no value
Declare yourCircle
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100; : Circle
radius: 5.0
yourCircle no value
: Circle
Create a new radius: 1.0
Circle object
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100; : Circle
radius: 5.0
yourCircle reference value
Assign object reference
to yourCircle : Circle
radius: 1.0
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100; : Circle
radius: 5.0
yourCircle reference value
: Circle
Change radius in radius: 100.0
yourCircle
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
Example 2: Defining Classes & Creating Objects
TV
channel: int The current channel (1 to 120) of this TV.
volumeLevel: int The current volume level (1 to 7) of this TV.
on: boolean Indicates whether this TV is on/off.
The + sign indicates Constructs a default TV object.
+TV()
a public modifier.
+turnOn(): void Turns on this TV.
+turnOff(): void Turns off this TV.
+setChannel(newChannel: int): void Sets a new channel for this TV.
+setVolume(newVolumeLevel: int): void Sets a new volume level for this TV.
+channelUp(): void Increases the channel number by 1.
Decreases the channel number by 1.
+channelDown(): void
Increases the volume level by 1.
+volumeUp(): void
Decreases the volume level by 1.
+volumeDown(): void
TV
TV
TestTV
Run
TestTV Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
Caution
Recall that, to invoke a method in the Math class, we use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
Can we invoke getArea() using SimpleCircle.getArea()?
The answer is no. All the methods used before this chapter were static
methods, which are defined using the static keyword. However,
getArea() is not static. It must be invoked from an object using
objectRefVar.methodName(arguments)
Example: myCircle.getArea()
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
Reference Data Fields
The data fields can be of primitive type or reference type
Example: The following Student class contains a data
field name of the String type, which is a reference type
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isMathMajor; // isMathMajor default value is false
char gender; // gender has default value '\u0000'
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Default Value for a Data Field
Type Default Value
Numeric 0 If a data field of a reference
boolean false type does not reference any
object, the data field holds
char '\u0000' a special literal value, null
Reference null
name? null
Example: age? 0
public class Test { isMathMajor? false
public static void main(String[] args) { gender?
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isMathMajor? " + student.isMathMajor);
System.out.println("gender? " + student.gender);
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
} rights reserved.
27
Example: Local Variables inside Methods
Java assigns no default value to local variables inside
methods
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);
}
}
Compile-time error:
variable not initialized
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
Differences between Variables of
Primitive Data Types & Object Types
Created using new Circle()
Primitive type int i = 1 i 1
Object type Circle c c reference c: Circle
radius = 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
Copying Variables of Primitive Data
Types & Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Object type assignment c1 = c2
Before: After:
c1 c1
c2 c2
c1: Circle c2: Circle c1: Circle c2: Circle
radius = 5 radius = 9 radius = 5 radius = 9
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
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. That object is now garbage
Garbage is automatically collected by JVM
TIP: If you know that an object is no longer needed,
you can explicitly assign null to its reference variable.
The JVM will automatically collect the space if the
object is not referenced by any variable
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31