ch10 Thinking in Objects

10-1 Introduction

10-2 Immutable Objects and Classes

The String class is immutable 物件產生之後,內容就不會改變

參考 p.368 程式 Listing Student.java

雖然 Student的每一個欄位都是 private, 且沒有 setter, 但是內容還是會改變

一個Class要成為 Immutable

10-3 The Scope of Variables

Variables 的類別

p.693 Figure 10.1 Members of a class can be declared in any order, with one exception

Hidden : Local 與 Instance 名字相同, 參考 page 369 的圖

避免使用,除了在method參數

10-4 The this Reference

重要 p.370 Figure 10.2 The keyword this refers to the calling object that invokes the method.

this.id = id;
// call another constructor
this(1.0);

10-5 Class Abstraction and Encapsulation

p.371 Figure 10.3 Class abstraction separates class implementation from the use of the class

p.372 Figure 10.4 The Loan class models the properties and behaviors of loans 提供 UML 讓使用者使用 Loan Class, 你不需要知道如何計算貸款後的每月償還金額

參考 p.372 程式 Listing 10.1 Loan.java

參考 p.373 程式 Listing 10.2 TestLoanClass.java

10-6 Object-Oriented Thinking

p.375 Figure 10. The BMI class encapsulates BMI information.

參考 p.376 程式 Listing 10.3 UseBMIClass.java

參考 p.376 程式 Listing 10.4 BMI.java

10-7 Object Composition

An object can contain another object, 例如 BMI 包含 String

重要 p.378 Figure 10.6 A student has a name and an address.

p.378 Figure 10.7 A person may have a supervisor.

p.379 Figure 10.8 A person may have several supervisors

10-8 Designing the Course Class

teaching by example and learning by doing

p.379 Figure 10.9 The Course class models the courses

參考 p.380 程式 Listing 10.5 TestCourse.java

參考 p.380 程式 Listing 10.6 Course.java

10-9 Designing a Class for Stacks

Stack 堆疊 last-in, first-out (LIFO)

p.381 Figure 10.10 A stack holds data in a last-in, first-out fashion

p.382 Figure 10.11 The StackOfIntegers class UML

參考 p.382 程式 Listing 10.7 TestStackOfIntegers.java

p.382 Figure 10.12 The StackOfIntegers class with array implementation

參考 p.383 程式 Listing 10.8 StackOfIntegers.java

10-10 Designing the GuessDate Class

p.384 Figure 10.13 The GuessDate class defines data for guessing birthdays.

參考 p.384 程式 Listing 10.9 UseGuessDateClass.java

參考 p.385 程式 Listing 10.10 GuessDate.java

10-11 Class Design Guidelines

10-11-1 Cohesion (凝聚)

10-11-2 Consistency (一致)

10-11-3 Encapsulation (隱藏)

10-11-4 Clarity (清晰)

10-11-5 Completeness (完整)

10-11-6 Instance vs. Static 的選擇