Chp10-Thinking in Objects
Chp10-Thinking in Objects
Thinking in Objects
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Motivations
You see the advantages of object-oriented programming
from the preceding chapter. This chapter will demonstrate
how to solve problems using the object-oriented paradigm.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
2
Objectives
To apply class abstraction to develop software (§10.2).
To explore the differences between the procedural paradigm and object-
oriented paradigm (§10.3).
To discover the relationships between classes (§10.4).
To design programs using the object-oriented paradigm (§§10.5–10.6).
To create objects for primitive values using the wrapper classes (Byte,
Short, Integer, Long, Float, Double, Character, and Boolean) (§10.7).
To simplify programming using automatic conversion between primitive
types and wrapper class types (§10.8).
To use the BigInteger and BigDecimal classes for computing very large
numbers with arbitrary precisions (§10.9).
To use the String class to process immutable strings (§10.10).
To use the StringBuilder and StringBuffer classes to process mutable
strings (§10.11).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
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.
4
Designing the Loan Class
Loan
-annualInterestRate: double The annual interest rate of the loan (default: 2.5).
-numberOfYears: int The number of years for the loan (default: 1)
-loanAmount: double The loan amount (default: 1000).
-loanDate: Date The date this loan was created.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Example: The Loan Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6
Example: The Loan Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
Example: TestLoan Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Object-Oriented Thinking
Chapters 1-8 introduced fundamental programming
techniques for problem solving using loops, methods, and
arrays. The studies of these techniques lay a solid
foundation for object-oriented programming. Classes
provide more flexibility and modularity for building
reusable software. This section improves the solution for a
problem introduced in Chapter 3 using the object-oriented
approach. From the improvements, you will gain the
insight on the differences between the procedural
programming and object-oriented programming and see
the benefits of developing reusable code using objects and
classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
The BMI Class
The get methods for these data fields are
provided in the class, but omitted in the
UML diagram for brevity.
BMI
-name: String The name of the person.
-age: int The age of the person.
-weight: double The weight of the person in pounds.
-height: double The height of the person in inches.
+BMI(name: String, age: int, weight: Creates a BMI object with the specified
double, height: double) name, age, weight, and height.
+BMI(name: String, weight: double, Creates a BMI object with the specified
height: double) name, weight, height, and a default age
20.
+getBMI(): double Returns the BMI
+getStatus(): String Returns the BMI status (e.g., normal,
overweight, etc.)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
Example: The BMI Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
Example: UseBMI Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Class Aggregation
An aggregation relationship is usually represented as a data field in the aggregating class. For example, the
relationship in Figure 10.6
...
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
Aggregation or Composition
Since aggregation and composition
relationships are represented using classes in
similar ways, many texts don’t differentiate
them and call both compositions.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
Aggregation Between Same Class
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.
1
Person
Supervisor
1
1
Person
Supervisor
m
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
Example: The Course Class
Course
-courseName: String The name of the course.
-students: String[] An array to store the students for the course.
-numberOfStudents: int The number of students (default: 0).
+Course(courseName: String) Creates a course with the specified name.
+getCourseName(): String Returns the course name.
+addStudent(student: String): void Adds a new student to the course.
+dropStudent(student: String): void Drops a student from the course.
+getStudents(): String[] Returns the students in the course.
+getNumberOfStudents(): int Returns the number of students in the course.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
Example: The Course Class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
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
Double once the objects are created.
Byte
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
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.
20
The Integer Class
and the Double Class
Constructors
Conversion Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string
representing the numeric value. The constructors
for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE. MAX_VALUE
represents the maximum value of the corresponding
primitive data type. For Byte, Short, Integer, and Long,
MIN_VALUE represents the minimum byte, short, int,
and long values. For Float and Double, MIN_VALUE
represents the minimum positive float and double values.
The following statements display the maximum integer
(2,147,483,647), the minimum positive float (1.4E-45),
and the maximum double floating-point number
(1.79769313486231570e+308d).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
Conversion Methods
Each numeric wrapper class implements the
abstract methods doubleValue, floatValue,
intValue, longValue, and shortValue, which
are defined in the Number class. These
methods “convert” objects into primitive
type values.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
The Static valueOf Methods
The numeric wrapper classes have a useful
class method, valueOf(String s). This method
creates a new object initialized to the value
represented by the specified string. For
example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
The Methods for Parsing Strings into
Numbers
You have used the parseInt method in the
Integer class to parse a numeric string into an
int value and the parseDouble method in the
Double class to parse a numeric string into a
double value. Each numeric wrapper class
has two overloaded parsing methods to parse
a numeric string into an appropriate numeric
value.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Automatic Conversion Between Primitive
Types and Wrapper Class Types
JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For
example, the following statement in (a) can be simplified as in (b):
Equivalent
Integer[] intArray = {new Integer(2), Integer[] intArray = {2, 4, 3};
new Integer(4), new Integer(3)};
Unboxing
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
BigInteger and BigDecimal
If you need to compute with very large integers or
high precision floating-point values, you can use
the BigInteger and BigDecimal classes in the
java.math package. Both are immutable. Both
extend the Number class and implement the
Comparable interface.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
BigInteger and BigDecimal
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
The String Class
Constructing a String:
String message = "Welcome to Java“;
String message = new String("Welcome to Java“);
String s = new String();
Obtaining String length and Retrieving Individual Characters in
a string
String Concatenation (concat)
Substrings (substring(index), substring(start, end))
Comparisons (equals, compareTo)
String Conversions
Finding a Character or a Substring in a String
Conversions between Strings and Arrays
Converting Characters and Numeric Values to Strings
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Strings Are Immutable
A String object is immutable; its contents cannot be changed.
Does the following code change the contents of the string?
String s = "Java";
s = "HTML";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
animation
Trace Code
String s = "Java";
s = "HTML";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
animation
Trace Code
String s = "Java";
s = "HTML";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Interned Strings
Since strings are immutable and are frequently
used, to improve efficiency and save memory, the
JVM uses a unique instance for string literals with
the same character sequence. Such an instance is
called interned. For example, the following
statements:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
Examples
String s1 = "Welcome to Java"; s1
: String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
animation
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Trace Code
s1
String s1 = "Welcome to Java"; : String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
Replacing and Splitting Strings
java.lang.String
+replace(oldChar: char, Returns a new string that replaces all matching character in this
newChar: char): String string with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String string with the new substring.
+split(delimiter: String): Returns an array of strings consisting of the substrings split by the
String[] delimiter.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
Examples
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string,
WABlcome.
"Welcome".replace("e", "AB") returns a new string,
WABlcomAB.
"Welcome".replace("el", "AB") returns a new string,
WABcome.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
Splitting a String
String[] tokens = "Java#HTML#Perl".split("#", 0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
displays
Java HTML Perl
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
Convert Character and Numbers
to Strings
The String class provides several static valueOf
methods for converting a character, an array of
characters, and numeric values to strings. These
methods have the same name valueOf with
different argument types char, char[], double, long,
int, and float. For example, to convert a double
value to a string, use String.valueOf(5.44). The
return value is string consists of characters ‘5’, ‘.’,
‘4’, and ‘4’.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
StringBuilder and StringBuffer
The StringBuilder/StringBuffer class is
an alternative to the String class. In general, a
StringBuilder/StringBuffer can be used wherever
a string is used. StringBuilder/StringBuffer is
more flexible than String. You can add, insert, or
append new contents into a string buffer, whereas
the value of a String object is fixed once the string
is created.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
StringBuilder Constructors
java.lang.StringBuilder
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
Modifying Strings in the Builder
java.lang.StringBuilder
+append(data: char[]): StringBuilder Appends a char array into this string builder.
+append(data: char[], offset: int, len: int): Appends a subarray in data into this string builder.
StringBuilder
+append(v: aPrimitiveType): StringBuilder Appends a primitive type value as a string to this
builder.
+append(s: String): StringBuilder Appends a string to this string builder.
+delete(startIndex: int, endIndex: int): Deletes characters from startIndex to endIndex.
StringBuilder
+deleteCharAt(index: int): StringBuilder Deletes a character at the specified index.
+insert(index: int, data: char[], offset: int, Inserts a subarray of the data in the array to the builder
len: int): StringBuilder at the specified index.
+insert(offset: int, data: char[]): Inserts data into this builder at the position offset.
StringBuilder
+insert(offset: int, b: aPrimitiveType): Inserts a value converted to a string into this builder.
StringBuilder
+insert(offset: int, s: String): StringBuilder Inserts a string into this builder at the position offset.
+replace(startIndex: int, endIndex: int, s: Replaces the characters in this builder from startIndex
String): StringBuilder to endIndex with the specified string.
+reverse(): StringBuilder Reverses the characters in the builder.
+setCharAt(index: int, ch: char): void Sets a new character at the specified index in this
builder.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
47
Examples
stringBuilder.append("Java");
stringBuilder.insert(11, "HTML and ");
stringBuilder.delete(8, 11) changes the builder to Welcome
Java.
stringBuilder.deleteCharAt(8) changes the builder to
Welcome o Java.
stringBuilder.reverse() changes the builder to avaJ ot
emocleW.
stringBuilder.replace(11, 15, "HTML")
changes the builder to Welcome to HTML.
stringBuilder.setCharAt(0, 'w') sets the builder to welcome
to Java.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48
The toString, capacity, length,
setLength, and charAt Methods
java.lang.StringBuilder
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49
Problem: Checking Palindromes
Ignoring Non-alphanumeric Characters
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
50