0% found this document useful (0 votes)
3 views

CH10 Thinking in Objects

--

Uploaded by

ahmedhesham43886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CH10 Thinking in Objects

--

Uploaded by

ahmedhesham43886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Chapter 10 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.

+Loan() Constructs a default Loan object.


+Loan(annualInterestRate: double, Constructs a loan with specified interest rate, years, and
numberOfYears: int, loan amount.
loanAmount: double)
+getAnnualInterestRate(): double Returns the annual interest rate of this loan.
+getNumberOfYears(): int Returns the number of the years of this loan.
+getLoanAmount(): double Returns the amount of this loan.
+getLoanDate(): Date Returns the date of the creation of this loan.
+setAnnualInterestRate( Sets a new annual interest rate to this loan.
annualInterestRate: double): void
+setNumberOfYears( Sets a new number of years to this loan.
numberOfYears: int): void
+setLoanAmount( Sets a new amount to this loan.
loanAmount: double): void
+getMonthlyPayment(): double Returns the monthly payment of this loan.
+getTotalPayment(): double Returns the total payment of this loan.

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;
}

/** Return loanAmount */


public double getLoanAmount() {
return loanAmount;
}
/** Set a newloanAmount */
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
.........
} Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 6
public class Loan {
……
/** Find monthly payment */
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 -
(Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
return monthlyPayment;
}
/** Find total payment */
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
/** Return loan date */
public java.util.Date getLoanDate() {
return loanDate;
}
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 7
import java.util.Scanner;
public class TestLoanClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter yearly interest rate, for example, 8.25: ");
double annualInterestRate = input.nextDouble();
System.out.print("Enter number of years as an integer: ");
int numberOfYears = input.nextInt();
System.out.print("Enter loan amount, for example, 120000.95: ");
double loanAmount = input.nextDouble();

Loan loan = new Loan(annualInterestRate, numberOfYears, loanAmount);


// Display loan date, monthly payment, and total payment
System.out.printf("The loan was created on %s\n" + "The monthly payment is
%.2f\nThe total payment is %.2f\n", loan.getLoanDate().toString(),
loan.getMonthlyPayment(), loan.getTotalPayment());
}
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 8
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, 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;

public BMI(String name, int age, double weight, double height) {


this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
}

public BMI(String name, double weight, double height) {


this(name, 20, weight, height);
}
………
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
public class BMI {
……

public double getBMI() {


double bmi = weight * KILOGRAMS_PER_POUND /
((height * METERS_PER_INCH) * (height * METERS_PER_INCH));
return Math.round(bmi * 100) / 100.0;
}

public String getStatus() {


double bmi = getBMI();
if (bmi < 18.5)
return "Underweight";
else if (bmi < 25)
return "Normal";
else if (bmi < 30)
return "Overweight";
else
return "Obese";
}
…… Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015
public class BMI {
……

public String getName() {


return name;
}

public int getAge() {


return age;
}

public double getWeight() {


return weight;
}

public double getHeight() {


return height;
}
}

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());

BMI bmi2 = new BMI("Peter King", 215, 70);


System.out.println("The BMI for " + bmi2.getName() + " is "
+ bmi2.getBMI() + " " + bmi2.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

Modifiers are used to indicate visibility of attributes and


operations.
➢ ‘+’ is used to denote Public visibility (everyone)
➢ ‘#’ is used to denote Protected visibility (friends and derived)
➢ ‘-’ is used to denote Private visibility (no one)

By default, attributes are hidden and operations are visible.

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)

Associations can be further classified


as
➢ Aggregation
➢ Composition

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

An aggregation relationship is usually represented as a data


field in the aggregating class

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

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
}
Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 24
IMPLEMENTING COMPOSITION AND AGGREGATION
RELATIONSHIP

Aggregation may exist between objects of the same class.


For example, a person may have a several supervisors

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

Represent relationship between instances of


classes
➢ Student enrolls in a course
➢ Courses have students
➢ Courses have exams
➢ Etc.

Association has two ends


➢ Role names (e.g. enrolls)
➢ Multiplicity (e.g. One course can have many students)
➢ Navigability (unidirectional, bidirectional)

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:

public class Name { public class Student { public class Address {


... private Name name; ...
} private Address address; }

...
}

Aggregated class Aggregating class Aggregated class

Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 36
Aggregation vs. Composition

◼Composition is really a strong form of association


➢components have only one owner
➢components cannot exist independent of their owner
➢components live or die with their owner
➢e.g. Each car has an engine that can not be shared with other cars.

◼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

You might also like