Chapter 6 Objects and Classes

Download Report

Transcript Chapter 6 Objects and Classes

Chapter 10 Thinking in Objects
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Motivations
You see the advantages of object-oriented
programming from the preceding two
chapters.
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
Objectives








To create immutable objects from immutable classes to protect
the contents of objects (§10.2).
To determine the scope of variables in the context of a class
(§10.3).
To use the keyword this to refer to the calling object itself
(§10.4).
To apply class abstraction to develop software (§10.5).
To explore the differences between the procedural paradigm and
object-oriented paradigm (§10.6).
To develop classes for modeling composition relationships
(§10.7).
To design programs using the object-oriented paradigm (§§10.810.10).
To design classes that follow the class-design guidelines
(§10.11).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Immutable Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its
class is called an immutable class.
If you delete the set method in the Circle class in the preceding
example, the class would be immutable because radius is
private and cannot be changed without a set method.
Immutable means unchangeable.
In Java, when an object is defined as being immutable it
means that once it has been initialized its state cannot be
changed.
Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) can
be made immutable by using the "final" keyword. Once they have been assigned a
value it cannot be changed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Example
public class Student {
/* if the class is immutable, then data field
must be private*/
/* the Student class has private data fields
and no set methods, but it is not an immutable
class */
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month,
day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
//below, dataCreated is retruned using the getDateCreated()
//this is a reference to a Date object. dataCreated can not brchanged
java.util.Date dataCreated =student.getDateCrreated ();
date.setYear(200000); // Now the student birth year is changed!
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
What Class is Immutable?
For a class to be immutable, it must mark all data fields
private and provide no mutator methods and no accessor
methods that would return a reference to a mutable data field
object.
Immutable objects are simply objects whose state (the
object's data) cannot change after construction. Examples
of immutable objects from the JDK include String and
Integer.
The Java Tutorial - Immutable Objects
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
Scope of Variables

The scope of instance and static variables is the
entire class. They can be declared anywhere inside
a class.

The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
initialized explicitly before it can be used.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
7
The this Keyword
 The
this keyword is the name of a reference that
refers to an object itself. One common use of the
this keyword is reference a class’s hidden data
fields.
 Another
common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8
this keyword
Sometimes a method will need to refer to the object that
is calling object itself.
 To allow this, Java defines the this keyword. this can be
used inside any method to refer to the current object. That
is, this is always a reference to the object on which the
method was invoked.
 You can use this anywhere a reference to an object of the
current class' type is permitted. To better understand what
this refers to, consider the following version of Box( ):

// A redundant use of this.
Box(double w, double h,
double d) {
The Java Tutorials –
this.width = w;
this.height = h;
this.depth = d;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
}
rights reserved. 0132130807
this keyword
9
Reference the Hidden Data Fields
public class Foo {
private int i = 5;
private static double k = 0;
void setI(int i) {
this.i = i;
}
Suppose that f1 and f2 are two objects of Foo.
Invoking f1.setI(10) is to execute
this.i = 10, where this refers f1
Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
Foo.k = k;
}
}
The this keyword provides a way to refer to the objhect that called
an instance method within the code of method.
• The line this.i=i means assign the value that calls the instances method setI.
• The Foo.k=k means that the value in parameter k is assigned to the static data field k of
the class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
10
Calling Overloaded Constructor
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
}
this is used to invoke another constructor
public double getArea() {
return this.radius * this.radius * Math.PI;
}
}
Every instance variable belongs to an instance represented by this,
which is normally omitted
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
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
is like a black box
hidden from the clients
Class
Class Contract
(Signatures of
public methods and
public constants)
Clients use the
class through the
contract of the class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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()
Constructs a default Loan object.
+Loan(annualInterestRate: double,
numberOfYears: int,
loanAmount: double)
Constructs a loan with specified interest rate, years, and
loan amount.
+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.
TestLoanClass
+setAnnualInterestRate(
Sets a new annual interest rate to this loan.
annualInterestRate: double): void
Sets a new number of years to this loan.
+setNumberOfYears(
numberOfYears: int): void
+setLoanAmount(
loanAmount: double): void
Sets a new amount to this loan.
+getMonthlyPayment(): double
Returns the monthly payment of this loan.
+getTotalPayment(): double
Returns the total payment of this loan.
Video – Loan and TestLoanClass –(Main Method)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Loan
Run
13
Object-Oriented Thinking
Chapters 1-6 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. Problem: Computing Body Mass Index (BMI) – Listing 3.5
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
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:
double, height: double)
Creates a BMI object with the specified
name, age, weight, and height.
Creates a BMI object with the specified
name, weight, height, and a default age
20.
+BMI(name: String, weight: double,
height: double)
+getBMI(): double
Returns the BMI
+getStatus(): String
Returns the BMI status (e.g., normal,
overweight, etc.)
BMI
UseBMIClass
Run
Video – body mass index (BMI) program
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
Example: The Course Class
Course
-name: String
The name of the course.
-students: String[]
The students who take the course.
-numberOfStudents: int
The number of students (default: 0).
+Course(name: String)
Creates a Course with the specified name.
+getName(): String
Returns the course name.
+addStudent(student: String): void Adds a new student to the course list.
+getStudents(): String[]
Returns the students for the course.
+getNumberOfStudents(): int
Returns the number of students for the course.
Course
TestCource
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Run
16
Case Study: Designing the Course Class
TestCourse & Course
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
/*A Course object can be created using the constructor Course (String
public Course(String courseName) {
name) by passing a course name.*/
this.courseName = courseName;
course1.addStudent("Peter Jones");
}
course1.addStudent("Brian Smith");
public void addStudent(String student) {
course1.addStudent("Anne Kennedy");
students[numberOfStudents] = student;
numberOfStudents++;
course2.addStudent("Peter Jones");
}
course2.addStudent("Steve Smith");
public String[] getStudents() {
return students;
System.out.println("Number of students in course1: "
}
+ course1.getNumberOfStudents());
public int getNumberOfStudents() {
String[] students = course1.getStudents();
return numberOfStudents;
for (int i = 0; i < course1.getNumberOfStudents(); i++) }
System.out.print(students[i] + ", ");
public String getCourseName() {
return courseName;
System.out.println();
}
System.out.print("Number of students in course2: "
public void dropStudent(String student) {
+ course2.getNumberOfStudents());
// Left as an exercise in Exercise 9.9
}
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
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.
Video – Designing a Class for Stacks
TestStackOfIntegers Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
Designing the StackOfIntegers Class
Data3
Data2
Data1
Data2
Data1
Data1
Data1
Data2
Data3
Data2
Data1
Data3
Data2
Data1
Data1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
19
Implementing
StackOfIntegers Class
elements[capacity – 1]
.
.
.
elements[size-1]
top
.
.
.
capacity
size
elements[1]
elements[0]
bottom
StackOfIntegers
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
20
Designing the GuessDate Class
GuessDate
-dates: int[][][]
The static array to hold dates.
+getValue(setNo: int, row: int,
column: int): int
Returns a date at the specified row and column in a given set.
public class GuessDate {
import java.util.Scanner;
private final static int[][][] dates = {
public class UseGuessDateClass {
{{ 1, 3, 5, 7}, { 9, 11, 13, 15},
{17, 19, 21, 23}, {25, 27, 29, 31}},
public static void main(String[] args) {
{{ 2, 3, 6, 7}, {10, 11, 14, 15}, {18, 19, 22, 23}, {26, 27, 30, 31}},
int date = 0; // Date to be determined
{{ 4, 5, 6, 7}, {12, 13, 14, 15}, {20, 21, 22, 23}, {28, 29, 30, 31}},
int answer;
{{ 8, 9, 10, 11}, {12, 13, 14, 15}, {24, 25, 26, 27}, {28, 29, 30, 31}},
// Create a Scanner
{{16, 17, 18, 19}, {20, 21, 22, 23}, {24, 25, 26, 27}, {28, 29, 30, 31}}};
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Is your birth date in Set" + (i + 1) + "?"); /** Prevent the user from creating objects from GuessDate */
for (int j = 0; j < 4; j++) {
private GuessDate() {
for (int k = 0; k < 4; k++)
}
System.out.print(GuessDate.getValue(i, j, k) + " ");
System.out.println();
/** Return a date at the specified row and column in a given set */
}
System.out.print("\nEnter 0 for No and 1 for Yes: ");
public static int getValue(int setNo, int k, int j) {
answer = input.nextInt();
return dates[setNo][k][j];
if (answer == 1)
}
date += GuessDate.getValue(i, 0, 0);
}
}
System.out.println("Your birth date is " + date);
}
}
Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
10.4 End of the chapter Program
(The MyPoint class)
10.4 – Design a class named MyPoint to represent a point
with x- and y-coordinates. Please refer to textbook.
Video – The MyPoint class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22