Professional Documents
Culture Documents
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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, Eleventh Edition, (c) 2017 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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 3
Class Abstraction and Encapsulation
● Class abstraction is separation of class
implementation from the use of the class.
● Class encapsulation: The details of implementation
are encapsulated and hidden from the user.
● The collection of public constructors, methods, and
data fields that are accessible from outside the class,
together with the description of how these members
are expected to behave, serves as the class's contract.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 4
Class Abstraction and Encapsulation
● Class creator provides documentation to:
– describe the class and,
– describe the use of the class
● The user of the class does not need to know how
the class is implemented.
● Implementation details are “encapsulated” and
hidden from the user.
Class implementation Class Contract
is like a black box (Signatures of Clients use the
hidden from the clients
Class public methods and class through the
public constants) contract of the class
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 5
Object-Oriented Thinking
● Chapters 1-8 introduced fundamental programming
techniques for problem solving using:
– loops
– methods
– arrays
● The techniques lay a solid foundation for object-
oriented programming.
● Classes provide more flexibility and modularity for
building reusable software.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
6
Class Relationships
Association
Aggregation
Composition
Inheritance (Chapter 11)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
7
Object Composition
● Composition is a special case of aggregation.
● Aggregation models has-a relationships; represents an
ownership relationship.
● The owner object is called an aggregating object and
its class an aggregating class.
● The subject object is called an aggregated object and
its class an aggregated class.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
8
Class Representation
An aggregation relationship is usually represented as a data
field in the aggregating class. For example, the relationship
in Figure 10.6 can be represented as follows:
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
9
Aggregation or Composition
● We refer aggregation between two objects
as composition if the existence of the
aggregated object is dependent on the
aggregating object.
● Many texts don’t differentiate them and
call both compositions.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
10
Aggregation Between Same Class
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
12
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.
Loan TestLoanClass
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 13
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.
Course TestCourse
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 14
Example: The
StackOfIntegers Class
StackOfIntegers
-elements: int[] An array to store integers in the stack.
-size: int The number of integers in the stack.
+StackOfIntegers() Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int) Constructs an empty stack with a specified capacity.
+empty(): boolean Returns true if the stack is empty.
+peek(): int Returns the integer at the top of the stack without
removing it from the stack.
+push(value: int): int Stores an integer into the top of the stack.
+pop(): int Removes the integer at the top of the stack and returns it.
+getSize(): int Returns the number of elements in the stack.
TestStackOfIntegers
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 15
Designing the StackOfIntegers Class
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 16
Implementing
StackOfIntegers Class
StackOfIntegers
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 17
Wrapper Classes
• Primitive data type values are not objects in
Java.
• However, many Java methods require the
use of objects as arguments.
• Java provides a wrapper class for each
primitive data type
– Wrap a primitive data type into an object.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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
Float classes are immutable, i.e., their
Short internal values cannot be changed
Byte Double once the objects are created.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 20
The Integer Class
and the Double Class
Constructors
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 22
Numeric Wrapper Class Constructors
• Examples:
Integer x = new Integer(2);
Integer x = new Integer("2");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 23
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 24
Numeric Wrapper Class Constants
• The following statement displays the
maximum integer 2,147,483,647.
– System.out.println(Integer.MAX_VALUE);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 25
Conversion Methods
• Each numeric wrapper class contains the methods doubleValue,
floatValue, intValue, longValue, and shortValue for returning a
double, float, int, long, or short value for the wrapper object.
• These methods “convert” objects into primitive type values.
• Examples:
Integer x = new Integer("2");
x.intValue() returns 2.
x.doubleValue() returns 2.0.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 26
The CompareTo Methods
• The numeric wrapper classes contain the
compareTo method for comparing two
numbers and returns 1 (greater than), 0
(equal to) or -1 (less than).
• Example:
Integer x1 = new Integer(2);
Integer x2 = new Integer(7);
x1.compareTo(x2) returns -1.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 27
The Static valueOf Methods
• The numeric wrapper classes have a useful static
method, valueOf(String s). This method creates
a new object initialized to the value represented
by the specified string.
• Examples:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 28
Parsing Strings into Numbers
• Each numeric wrapper class has two overloaded parsing
methods to parse a numeric string into an appropriate
numeric value.
• In the Integer class:
public static int parseInt(String s) //radix: 10
public static int parseInt(String s, int radix) //radix: 2, 8, 16
• In the Double class:
public static double parseDouble(String s) //radix: 10
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 29
Parsing Strings into Numbers
• Examples:
int x = Integer.parseInt("11");
System.out.println(x); //prints 11
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 30
Automatic Conversion Between Primitive Types and
Wrapper Class Types
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 31
Automatic Conversion Between Primitive
Types and Wrapper Class Types
Unboxing
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 32
BigInteger and BigDecimal
• The largest integer of the long type is
9223372036854775807.
• 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.
– An instance of BigInteger can represent an integer of any
size.
– Use the add, subtract, multiply, divide, and remainder
methods to perform arithmetic operations.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 33
BigInteger
Output: 18446744073709551614
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 34
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 35
Example
The factorial of an integer can be very large. This
program gives a method that can return the
factorial of any integer.
LargeFactorial
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 36
The String Class
• The class String is used for processing
strings.
• This class has 13 constructors and more
than 40 methods for manipulating strings.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 37
Constructing Strings
• To create a string from a string literal, use
the syntax:
String newString = new String(stringLiteral);
• Example:
String message = new String("Welcome to Java");
• Since Java treats a string literal as a String object,
the following statement is valid.
String message = "Welcome to Java";
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 38
Constructing Strings
A string can also be created from an array of
characters.
Example:
char [ ] charArray = {'J', 'a', 'v', 'a'};
String message = new String(charArray);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 39
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 40
Trace Code
String s = "Java";
s = "HTML";
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 41
Trace Code
String s = "Java";
s = "HTML";
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 42
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 43
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 44
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 45
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 46
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 47
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 replaces 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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 48
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 49
Splitting a String
String[] tokens = "Java#HTML#Perl".split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
displays
Java HTML Perl
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 50
Matching, Replacing and Splitting by Patterns
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 51
Matching, Replacing and Splitting by Patterns
The replaceAll, replaceFirst, and split methods can be used with
a regular expression. For example, the following statement
returns a new string that replaces $, +, or # in "a+b$#c" by the
string NNN.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 52
Matching, Replacing and Splitting by Patterns
The following statement splits the string into an array of strings
delimited by some punctuation marks.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 53
Convert Character and Numbers to Strings
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 54
Convert Character and Numbers to Strings
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 55
Formatting Strings
• The String class contains the static format method
to return a formatted string.
• This method is similar to the printf method except
the format method returns a formatted string.
• Syntax to invoke the format method:
String.format(format, item1, item2, ..., itemk);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 56
Formatting Strings
String s = String.format("%7.2f%6d%-4s", 45.556,
14, "AB");
System.out.println(s);
//displays 45.56 14AB
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 57
StringBuilder and StringBuffer
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 58
StringBuilder and StringBuffer
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 59
StringBuilder Constructors
java.lang.StringBuilder
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 60
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, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 61
Examples
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 62
Examples
s.insert(11, "HTML"); inserts HTML at index 11.
s.delete(8, 11) deletes the characters from index 8 to 10.
s.deleteCharAt(8) deletes the character at index 8.
s.reverse() reverse the string builder.
s.replace(11, 15, "HTML")
replace the characters from index 11 to 14 with HTML.
s.setCharAt(0, 'w') changes the first character to w.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 63
The toString, capacity, length,
setLength, and charAt Methods
java.lang.StringBuilder
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 64
Problem: Checking Palindromes
PalindromeIgnoreNonAlphanumeric
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 65
import java.util.Scanner;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 66
public static String filter(String s) {
StringBuilder s1 = new StringBuilder();
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 67