Professional Documents
Culture Documents
Lecture 04
Thinking in Objects (1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Chapter 10 Thinking in Objects
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
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.
Before studying these examples, we first introduce
several language features for supporting these
examples
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
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. 4
Class Abstraction & 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
Example: The use of a PC does not require the
knowledge of its internal workings
Class implementation Class Contract
is like a black box (Signatures of Clients use the
hidden from the Class public methods and class through the
clients public constants) contract of the class
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
A specific loan can be
viewed as an object of a
Example: The Loan Class
Loan class. The interest Loan
rate, amount, and period -annualInterestRate: double The annual interest rate of the loan (default: 2.5).
-numberOfYears: int The number of years for the loan (default: 1)
are its properties, and -loanAmount: double The loan amount (default: 1000).
computing the monthly -loanDate: Date The date this loan was created.
& total payments are its
+Loan() Constructs a default Loan object.
methods. When you buy +Loan(annualInterestRate: double, Constructs a loan with specified interest rate, years, and
a car, a loan object is numberOfYears: int, loan amount.
loanAmount: double)
created by instantiating +getAnnualInterestRate(): double Returns the annual interest rate of this loan.
the class with your loan +getNumberOfYears(): int Returns the number of the years of this loan.
interest rate, amount, and +getLoanAmount(): double Returns the amount of this loan.
period. You can then use +getLoanDate(): Date Returns the date of the creation of this loan.
+setAnnualInterestRate( Sets a new annual interest rate to this loan.
the methods to find the annualInterestRate: double): void
monthly & total +setNumberOfYears( Sets a new number of years to this loan.
numberOfYears: int): void
payments. As a user of +setLoanAmount( Sets a new amount to this loan.
the Loan class, you loanAmount: double): void
don’t need to know how +getMonthlyPayment(): double Returns the monthly payment of this loan.
+getTotalPayment(): double Returns the total payment of this loan.
these methods are
implemented Loan TestLoanClass Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Aggregation Composition
A "uses" B. B exists A "owns" B. B has no
independently meaning or purpose in the
(conceptually) from A system without A
Example: A Company is an Example: A Text Editor
aggregation of People owns a Buffer (composition)
A Company is a A Text Editor uses a File
composition of Accounts (aggregation)
When a Company ceases to When Text Editor is closes,
do business its Accounts the Buffer is destroyed but
cease to exist but its People the File is not
continue to exist
Source: programmers.stackexchange.com/questions/61376/aggregation-vs-composition/61527#61527
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Aggregation & Composition
Composition is actually a special case of the aggregation
relationship
Aggregation models has-a relationships and represents an
ownership relationship between two objects
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
Composition Aggregation
1 1 1..3 1
Name Student Address
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Aggregation & Composition
Composition Aggregation
1 1 1..3 1
Name Student Address
...
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Aggregation Between Same Class
What happens if a person has several supervisors?
1
Person
Supervisor
m
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
Example: The Course Class
The Course class Course
encapsulates the -courseName: String The name of the course.
internal -students: String[] An array to store the students for the course.
-numberOfStudents: int The number of students (default: 0).
implementation. The
+Course(courseName: String) Creates a course with the specified name.
user can create a +getCourseName(): String Returns the course name.
Course object and +addStudent(student: String): void Adds a new student to the course.
manipulate it through +dropStudent(student: String): void Drops a student from the course.
+getStudents(): String[]
the public methods Returns the students in the course.
+getNumberOfStudents(): int Returns the number of students in the course.
addStudent,
dropStudent,
This example uses an array to store students,
getNumOfStudents
but you could use a different data structure to
and getStudents.
store students. The program that uses
However, the user
Course does not need to change as long as
doesn’t need to know
the contract of the public methods remains
how these methods are
unchanged
implemented Course TestCourse Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Example: Stack of Integers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
Stack of Integers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Wrapper Classes
Wrapper classes are used when an object
representation of a primitive data type is required
1. Boolean
Wrapper classes do not 2. Character
have no-arg constructors 3. Short
The instances of all 4. Byte
wrapper classes are 5. Integer
immutable 6. Long
7. Float
8. Double
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
The Integer & 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 & Double Classes
Constructors
Class Constants MAX_VALUE, MIN_VALUE
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
MIN_VALUE & MAX_VALUE
MAX_VALUE represents the maximum value of the
corresponding numeric primitive data type
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
Conversion from Numeric String to Object
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
Examples:
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
Parsing Strings into Numbers
We 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
(a) (b)
Boxing (automatic primitive type to object conversion
Lecture 05
Thinking in Objects (2)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
BigInteger & BigDecimal Classes
If you need to compute with very large integers
or high precision floating-point values, you can
use the BigInteger and BigDecimal classes
of the java.math package
Both are immutable
Both extend the Number abstract class and
implement the Comparable interface
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
BigInteger & BigDecimal Classes
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 *
2
System.out.println(c);
LargeFactorial Run
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();
length()
concat()
equals(), compareTo()
charAt()
substring(index), substring(start, end)
Finding a character or a substring in a string
String conversions
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
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Example: Interned Strings
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";
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 & Splitting Strings
java.lang.String
+replace(oldChar: char, Returns a new string that replaces all matching oldChar in this
newChar: char): String string with the newChar.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching oldString in
newString: String): String this string with the newString substring.
+replaceAll(regex: String, Returns a new string that replace all matching regex in this string
newString: String): String with the newString.
+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: Replacing Substrings
Replace all occurrences of a character in a string
"Welcome".replace('e', 'A') returns a new string, WAlcomA
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Example: Splitting a String
displays
Java HTML Perl
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 43
Matching, Replacing & Splitting by Patterns
You can match, replace, or split a string by specifying
a pattern
This is an extremely useful and powerful feature,
commonly known as regular expression. For this
reason, two simple patterns are used in this section
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*");
"Java is cool".matches("Java.*");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 44
Matching, Replacing & 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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 45
Matching, Replacing & Splitting by Patterns
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 47
StringBuilder & StringBuffer Classes
The StringBuilder and StringBuffer classes are an
alternative to the String class
In general, they can be used wherever a String is used
They are more flexible than String. You can add, insert,
or append new contents into a StringBuilder or
StringBuffer, whereas the value of a String object is
fixed once it is created
StringBuffer is appropriate for threaded applications,
and StringBuilder for all others
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 48
StringBuilder Constructors
java.lang.StringBuilder
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 49
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. 50
Examples: Modifying Strings in the Builder
stringBuilder.append("Welcome to Java") initializes the builder
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 52
Example: Checking Palindromes
Ignoring Non-alphanumeric Characters
PalindromeIgnoreNonAlphanumeric Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 53