CH10 Thinking in Objects
CH10 Thinking in Objects
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 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, Global Edition. © Pearson Education Limited 2015 2
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.
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, Tenth Edition, Global Edition. © Pearson Education Limited 2015 3
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, Global Edition. © Pearson Education Limited 2015 4
public class Loan {
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
public Loan() {
this(2.5, 1, 1000);
}
public Loan(double annualInterestRate, int numberOfYears,double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
……….
} Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 5
public class Loan {
……
/** Return numberOfYears */
public int getNumberOfYears() {
return numberOfYears;
}
/** Set a new numberOfYears */
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
+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, Global Edition. © Pearson Education Limited 2015 9
public class BMI {
private String name;
private int age;
private double weight; // in pounds
private double height; // in inches
public static final double KILOGRAMS_PER_POUND = 0.45359237;
public static final double METERS_PER_INCH = 0.0254;
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
public class UseBMIClass {
public static void main(String[] args) {
BMI bmi1 = new BMI("John Doe", 18, 145, 70);
System.out.println("The BMI for " + bmi1.getName() + " is "
+ bmi1.getBMI() + " " + bmi1.getStatus());
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
Class diagram
A class diagram depicts classes and their
interrelationships
Used for describing structure and behavior in the
use cases
Provide a conceptual model of the system in terms
of entities and their relationships
Detailed class diagrams are used for developers
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
Class diagram: UML
Each class is represented by a rectangle subdivided into three
compartments
➢ Name
➢ Attributes
➢ Operations
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
Class diagram
Name
Account_Name
- Customer_Name
Attributes
- Balance
+addFunds( ) Operations
+withDraw( )
+transfer( )
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
OO Relationships
There are two kinds of Relationships
➢ Generalization (parent-child relationship)
➢ Association (student enrolls in course)
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
ASSOCIATION
Association is a general binary relationship that
describes an activity between two classes.
Example:
– A student taking a course is an association between the
Student class and the Course class.
– A faculty member teaching a course is an association
between the Faculty class and the Course class.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 18
ASSOCIATION
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 19
ASSOCIATION: Implementation
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 20
AGGREGATION
Aggregation is a special form of association that represents an ownership
relationship between two objects.
The owner object is called an aggregating object, and its class is called an
aggregating class.
The subject object is called an aggregated object, and its class is called an
aggregated class.
Example: “a student has an address” is an aggregation relationship between
the Student class and the Address class, since an address can be shared by
several students.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 21
COMPOSITION
If an object is exclusively owned by an aggregating object, the
relationship between the object and its aggregating object is
referred to as a composition.
For example, “a student has a name” is a composition
relationship between the Student class and the Name class
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 22
IMPLEMENTING COMPOSITION AND AGGREGATION
RELATIONSHIP
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 23
IMPLEMENTING COMPOSITION AND
AGGREGATION RELATIONSHIP
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.
1
Person
Supervisor
1
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 25
EXERCISE
Classify the following into association (A), aggregation
(AG), or composition (C):
– A country has a capital city
– A dining philosopher uses a fork
– Files contain records
– A polygon is composed of an ordered set of points
– A person uses a computer language on a project
– Each dog has a name
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 26
INHERITANCE
Inheritance enables you to define a general class (i.e., a
superclass) and later extend it to more specialized classes (i.e.,
subclasses).
Different classes may have some common properties and
behaviors, which can be generalized in a class that can be shared
by other classes.
The specialized classes inherit the properties and methods from
the general class.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 27
EXAMPLE
Suppose you want to design the classes to model geometric objects
such as circles and rectangles.
A general class GeometricObject can be used to model all
geometric objects.
– This class contains the properties color and filled and their appropriate getter
and setter methods.
– Assume that this class also contains the dateCreated property and the
getDateCreated() and toString() methods.
– The toString() method returns a string representation of the object.
The Circle class and Rectangle class extends the GeometricObject
class.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 28
UML CLASS DIAGRAM
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 29
More explanation
on
Classes Relationships
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 30
OO Relationships: Association
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
Association: Multiplicity and Roles
student
1 *
University Person
0..1 *
employer teacher
Multiplicity
Role
Symbol Meaning
1 One and only one
Role
0..1 Zero or one “A given university groups many people; some
act as students, others as teachers. A given
M..N From M to N (natural language)
student belongs to a single university; a given
* From zero to any positive integer teacher may or may not be working for the
0..* From zero to any positive integer university at a particular time.”
1..* From one to any positive integer
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
Association: Model to Implementation
* 4
Student Course
has enrolls
Class Student {
Course enrolls[4];
}
Class Course {
Student have[];
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
OO Relationships: Composition
Class W
Whole Class
Association
Models the part–whole relationship
Class P1 Class P2
Composition
Also models the part–whole relationship but, in
addition, Every part may belong to only one
whole, and If the whole is deleted, so are the
Part Classes parts
Example
Example:
A number of different chess boards: Each square
belongs to only one board.
If a chess board is thrown away, all 64 squares on
that board go as well.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
OO Relationships: Aggregation
Container Class
Class C
AGGREGATION Aggregation:
expresses a relationship among instances of related
classes. It is a specific kind of Container-
Class E1 Class E2 Containee relationship.
I.e. Aggregation models has-a relationships
and represents an ownership relationship
Containee Classes between two objects
Example
Bag
express a more informal relationship than
composition expresses.
Apples Milk
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
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, Tenth Edition, Global Edition. © Pearson Education Limited 2015 36
Aggregation vs. Composition
◼Aggregations
may form "part of" the association, but may not be essential to it. They
may also exist independent of the aggregate. e.g. Apples may exist
independent of the bag.
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
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, Global Edition. © Pearson Education Limited 2015 38
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String getCourseName() {
public String[] getStudents() {
return courseName;
return students;
}
}
public int getNumberOfStudents() {
public void dropStudent(String student) {
return numberOfStudents;
// Left as an exercise in Exercise 9.9
}
}
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
course1.addStudent("Peter Jones");
course1.addStudent("Brian Smith");
course1.addStudent("Anne Kennedy");
course2.addStudent("Peter Jones");
course2.addStudent("Steve Smith");
System.out.println("Number of students in course1: "
+ course1.getNumberOfStudents());
String[] students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students[i] + ", ");
System.out.println();
System.out.print("Number of students in course2: "
+ course2.getNumberOfStudents());
}
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 40