Chapter 9 Objects and Classes
Chapter 9 Objects and Classes
Chapter 9 Objects and Classes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Motivations
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 you program it?
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 Math, String, Character, Date(§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 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).
To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float,
Double, Character, and Boolean)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
OO Programming Concepts
Object-oriented programming (OOP) involves
programming using objects. An object represents
an entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle,
a button, and even a loan can all be viewed as
objects. An object has a unique identity, state, and
behaviors. The state of an object consists of a set
of data fields (also known as properties) with their
current values. The 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
Objects
Class Name: Circle A class template
Data Fields:
radius is _______
Methods:
getArea
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
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 the class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
TestSimpleCircle Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Constructors
Constructors are a special
Circle() { kind of methods that are
} invoked to construct objects.
Circle(double newRadius) {
radius = newRadius;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
Creating Objects Using
Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
Default Constructor
A class may be defined without constructors. In
this case, a no-arg constructor with an empty body
is implicitly defined in the class. This constructor,
called a 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.
12
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
Accessing Object’s Members
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
Differences between Variables of
Primitive Data Types and Object Types
Created using new Circle()
Primitive type int i = 1 i 1
radius = 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Before: After:
c1 c1
c2 c2
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
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.
Garbage is automatically collected by JVM.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
The Math Class
Class constants:
– PI
–E
Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
Trigonometric Methods
sin(double a) Examples:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
Rounding Methods
double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
int round(float x)
Return (int)Math.floor(x+0.5).
long round(double x)
Return (long)Math.floor(x+0.5).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
min, max, and abs
max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters.
Math.max(2, 3) returns 3
abs(a) Math.max(2.5, 3) returns
Returns the absolute value of the 3.0
parameter. Math.min(2.5, 3.6)
random() returns 2.5
Returns a random double value Math.abs(-2) returns 2
in the range [0.0, 1.0). Math.abs(-2.1) returns
2.1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
The random Method
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
Escape Sequences for Special Characters
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
Methods in the Character Class
Method Description
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the
System class and Scanner class. The String type is not a primitive
type. It is known as a reference type. Any Java class can be used
as a reference type for a variable. Reference data types will be
thoroughly discussed in Chapter 9, “Objects and Classes.” For the
time being, you just need to know how to declare a String variable,
how to assign a string to the variable, how to concatenate strings,
and to perform simple operations for strings.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
Simple Methods for String Objects
Method Description
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
Simple Methods for String Objects
Strings are objects in Java. The methods in the preceding
table can only be invoked from a specific string instance.
For this reason, these methods are called instance methods.
A non-instance method is called a static method. A static
method can be invoked without using an object. All the
methods defined in the Math class are static methods. They
are not tied to a specific object instance. The syntax to
invoke an instance method is
referenceVariable.methodName(arguments).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Getting Characters from a String
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
Converting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
String Concatenation
String s3 = s1.concat(s2); or String s3 = s1 + s2;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Reading a String from the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
Reading a Character from the
Console
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Comparing Strings
Method Description
OrderTwoCities Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
Obtaining Substrings
Method Description
substring(beginIndex) Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string, as shown in Figure 4.2.
substring(beginIndex, Returns this string’s substring that begins at the specified beginIndex and
endIndex) extends to the character at index endIndex – 1, as shown in Figure 9.6.
Note that the character at endIndex is not part of the substring.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Finding a Character or a Substring
in a String
Method Description
indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
lastIndexOf(ch, Returns the index of the last occurrence of ch before fromIndex in this
fromIndex) string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
Finding a Character or a Substring
in a String
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
Conversion between Strings and
Numbers
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
The Date Class
Java provides a system-independent encapsulation of date
and time in the java.util.Date class. You can use the Date
class to create an instance for the current date and time and
use its toString method to return the date and time as a string.
java.util.Date
The + sign indicates
public modifer +Date() Constructs a Date object for the current time.
+Date(elapseTime: long) Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String Returns a string representing the date and time.
+getTime(): long Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void Sets a new elapse time in the object.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
The Date Class Example
For example, the following code
java.util.Date date = new java.util.Date();
System.out.println(date.toString());
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
Instance
Variables, and Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
Static Variables, Constants,
and Methods, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
47
Why Data Fields Should Be
private?
To protect data.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.
CircleWithPrivateDataFields
TestCircleWithPrivateDataFields Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
50
The this Keyword
The this keyword is the name of a reference that
refers to an object itself. One common use of the
this keyword is reference a class’s hidden data
fields.
Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
51
Class Abstraction and Encapsulation
Class 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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
52
Wrapper Classes
Boolean Integer NOTE: (1) The wrapper classes do
not have no-arg constructors. (2)
Character Long The instances of all wrapper
classes are immutable, i.e., their
Short Float internal values cannot be changed
once the objects are created.
Byte Double
Wrapper classes are used to convert any data type into an object.
The primitive data types are not objects; they do not belong to
any class; they are defined in the language itself. Sometimes, it is
required to convert data types into objects in Java language
Applications:
1) To convert simple data types into objects, that is, to give object
form to a data type; here constructors are used.
2) To convert strings into data types (known as parsing
operations), here methods of type parseXXX() are used.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
53
The Integer and Double Classes
java.lang.Integer java.lang.Double
-value: int -value: double
+MAX_VALUE: int +MAX_VALUE: double
+MIN_VALUE: int +MIN_VALUE: double
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
54
Why Data Fields Should Be
private?
To protect data.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
55
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.
CircleWithPrivateDataFields
TestCircleWithPrivateDataFields Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
56
References
Chapter 4 - Math, Character and String Classes
Chapters 9, 10 – Object, Classes , Wrapper
Classess
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
57