Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Motivations
You see the advantages of object-oriented programming from the preceding two chapters. This chapter will demonstrate how to solve problems using the objectoriented 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
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Example
public class Student { private int id; private BirthDate birthDate;
public class BirthDate { private int year; private int month; private int day;
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 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); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
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
this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a classs 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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
10
Class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
11
+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 +getMonthlyPayment(): double +getTotalPayment(): double Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan.
Loan
TestLoanClass
Run
12
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
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. 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
13
BMI
UseBMIClass
Run
14
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
+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
Run
15
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
An array to store integers in the stack. The number of integers in the stack. Constructs an empty stack with a default capacity of 16. Constructs an empty stack with a specified capacity. Returns true if the stack is empty. Returns the integer at the top of the stack without removing it from the stack. Stores an integer into the top of the stack. Removes the integer at the top of the stack and returns it. Returns the number of elements in the stack.
TestStackOfIntegers
Run
16
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Data1
Data2 Data1
Data2
Data1
Data1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
17
. . .
elements[size-1] top capacity
. . .
elements[1] elements[0] bottom
size
StackOfIntegers
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
18
GuessDate
UseGuessDateClass
Run
19
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Designing a Class
(Coherence)
A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. You can use a class for students, for example, but you should not combine students and staff in the same class, because students and staff have different entities.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
20
(Separating responsibilities) A single entity with too many responsibilities can be broken into several classes to separate responsibilities. The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities. The String class deals with immutable strings, the StringBuilder class is for creating mutable strings, and the StringBuffer class is similar to StringBuilder except that StringBuffer contains synchronized methods for updating strings.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
21
are designed for reuse. Users can incorporate classes in many different combinations, orders, and environments. Therefore, you should design a class that imposes no restrictions on what or when the user can do with it, design the properties to ensure that the user can set properties in any order, with any combination of values, and design methods to function independently of their order of occurrence.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
22
a public no-arg constructor and override the equals method and the toString method defined in the Object class whenever possible.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
23
standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
24
Each class can present two contracts one for the users of the class and one for the extenders of the class. Make the fields private and accessor methods public if they are intended for the users of the class. Make the fields or method protected if they are intended for extenders of the class. The contract for the extenders encompasses the contract for the users. The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
25
class should use the private modifier to hide its data from direct access by clients. You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify. A class should also hide methods not intended for client use. The gcd method in the Rational class in Example 11.2, The Rational Class, is private, for example, because it is only for internal use within the class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
26
property that is shared by all the instances of the class should be declared as a static property.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
27