the basics of object- oriented programming eric jui-lin lu, ph.d. department of management...

34
The Basics of The Basics of Object-Oriented Object-Oriented Programming Programming Eric Jui-Lin Lu, Ph.D. Department of Management Information Systems National Chung Hsing University

Post on 21-Dec-2015

219 views

Category:

Documents


3 download

TRANSCRIPT

The Basics of The Basics of Object-Oriented Object-Oriented ProgrammingProgramming

Eric Jui-Lin Lu, Ph.D.

Department of Management Information Systems

National Chung Hsing University

2

Object-Oriented Object-Oriented ProgrammingProgramming

物件導向程式設計(物件導向程式設計( object-oriented object-oriented programmingprogramming )是一種以物件為核心的程式設)是一種以物件為核心的程式設計方式,這一類的程式會利用一個或者一個以上計方式,這一類的程式會利用一個或者一個以上的物件來完成工作。的物件來完成工作。 這一類程式設計的一項重點就是找出所需要的物件這一類程式設計的一項重點就是找出所需要的物件 當需要一個以上的物件來完成一個工作時,這些物件當需要一個以上的物件來完成一個工作時,這些物件

之間會互相呼叫(也稱之為傳送訊息,之間會互相呼叫(也稱之為傳送訊息, send send messagemessage )來互動)來互動

Object (or entity, instance) Object (or entity, instance) 也就是物件、實體。也就是物件、實體。 例如:汽車、人、表單等等例如:汽車、人、表單等等

3

ObjectsObjects 每一個物件都擁有特性(一般稱之為屬性 每一個物件都擁有特性(一般稱之為屬性

attributeattribute )以及行為(一般稱之為 )以及行為(一般稱之為 method method 或或者 者 functionfunction )) 例如:描述汽車的方式有廠牌、排氣量、顏色等,汽例如:描述汽車的方式有廠牌、排氣量、顏色等,汽

車的行為有加速、煞車等車的行為有加速、煞車等 例如:描述學生的方式有姓名、學號、系別、年級、例如:描述學生的方式有姓名、學號、系別、年級、

連絡住址、身高、體重等,學生的行為有選課、更改連絡住址、身高、體重等,學生的行為有選課、更改住址等住址等

每一個物件的特性值說明該物件的狀態每一個物件的特性值說明該物件的狀態 我的汽車是 我的汽車是 HondaHonda,, 1600cc1600cc ,灰色的轎車,灰色的轎車 資管系周潔輪今年是二年級,他的學號是 資管系周潔輪今年是二年級,他的學號是 1122334411223344 。。

4

ClassesClasses 從一個實體中萃取出我們有興趣的特性以及行為的過程,從一個實體中萃取出我們有興趣的特性以及行為的過程,

我們稱之為我們稱之為抽象化抽象化(( abstractionabstraction )) 以學生為例,如果我們今天要完成的系統是保健室的登錄系統,以學生為例,如果我們今天要完成的系統是保健室的登錄系統,

那麼我們需要從學生萃取出來的特色應該有姓名、學號、身高、那麼我們需要從學生萃取出來的特色應該有姓名、學號、身高、和體重。可是如果要完成的系統是學生選課系統,那麼我們不會和體重。可是如果要完成的系統是學生選課系統,那麼我們不會對身高和體重有興趣,自然不需要把這些特色定義出來。對身高和體重有興趣,自然不需要把這些特色定義出來。

我們需要對每一個物件都進行定義嗎?我們需要對每一個物件都進行定義嗎? 以一個有一萬多人的學校,要為每一個學生物件都進行定義的話,以一個有一萬多人的學校,要為每一個學生物件都進行定義的話,

這是非常耗時的。這是非常耗時的。 其實,以一個特定系統而言(例如之前所說的選課系統),每一其實,以一個特定系統而言(例如之前所說的選課系統),每一

個學生物件的特色以及行為都是相同的。如果為每一個學生物件個學生物件的特色以及行為都是相同的。如果為每一個學生物件都定義的話,幾乎都是重複的。都定義的話,幾乎都是重複的。

因此,同一類的物件的特色以及行為的定義就統一的定義在因此,同一類的物件的特色以及行為的定義就統一的定義在類別類別(( classclass )裡。)裡。

5

Object-Oriented ModelObject-Oriented Model 要使用物件來完成工作以前,類別必須先被定義要使用物件來完成工作以前,類別必須先被定義

出來。出來。 在寫物件導向程式的時候,在寫物件導向程式的時候,

一般來說,會建議使用現成的類別。在 一般來說,會建議使用現成的類別。在 Java Java 的套件的套件中,已經擁有數千個類別的定義。中,已經擁有數千個類別的定義。

如果現成的類別不存在,我們就自己定義類別。如果現成的類別不存在,我們就自己定義類別。 因此,因此, Java Java 的每一個程式都是一個類別的每一個程式都是一個類別 在 在 Java Java 的程式中,我們最少需要一個類別,這的程式中,我們最少需要一個類別,這

個類別控制整個程式的流程,例如先取得使用者個類別控制整個程式的流程,例如先取得使用者的輸入,利用物件完成工作,最後把結果呈現出的輸入,利用物件完成工作,最後把結果呈現出來。這個類別也因此稱之為控制類別(來。這個類別也因此稱之為控制類別( control control classclass )。)。

6

Hello WorldHello World

// class 是表明類別的保留字class HelloWorld { public static void main(String[] args) { // System 是 JDK 提供的類別 // System.out 是代表一個物件,也就是標準輸出 System.out.println(“ Hello World” ); }}

7

Use of Date ClassUse of Date Class

// 將系統時間顯示出來// 利用一個現成的物件 System.out,以及產生一個新的物件 d// 利用物件之間的互動,將工作完成class DisplayDate { public static void main(String[] args) { java.util.Date d = new java.util.Date(); System.out.println(d.toString()); }}

8

An ExampleAn Example

A worker is paid at the hourly rate of $8 per A worker is paid at the hourly rate of $8 per hour for the first 35 hours worked. Overtime hour for the first 35 hours worked. Overtime is paid at 1.5 times the hourly rate for the is paid at 1.5 times the hourly rate for the next 25 hours worked and paid at 2 times the next 25 hours worked and paid at 2 times the hourly rate for additional hours worked. hourly rate for additional hours worked. Write a program to input the number of Write a program to input the number of hours worked; then calculate and output the hours worked; then calculate and output the total amount paid. total amount paid. 物件是什麼?物件是什麼? 描述這個物件的屬性是什麼?描述這個物件的屬性是什麼? 這個物件的行為是什麼?這個物件的行為是什麼?

9

Object-Oriented ModelObject-Oriented Model

開始定義這個物件的類別。這個類別,我們一開始定義這個物件的類別。這個類別,我們一般稱之為模式類別(般稱之為模式類別( model classmodel class )。)。

產生一個控制類別,在這個控制類別中,我們產生一個控制類別,在這個控制類別中,我們取得使用者輸入的資料,然後產生一個物件取得使用者輸入的資料,然後產生一個物件(也就是產生一個之前定義的模式類別的一個 (也就是產生一個之前定義的模式類別的一個 instanceinstance ),並設定這個物件的值之後,要求),並設定這個物件的值之後,要求物件計算出薪資總額。物件計算出薪資總額。 因為要用到 因為要用到 Input Input 以及 以及 OutputOutput ,我們也可以使,我們也可以使

用 用 JDK JDK 提供的 提供的 IO IO 類別,這一類的類別也稱之為 類別,這一類的類別也稱之為 View ClassView Class..

10

Object-Oriented ModelObject-Oriented Model JDK JDK 提供的 提供的 IO classes IO classes 有有

JOptionPaneJOptionPane String s = JOptionPane.showInputDialog(“Enter String s = JOptionPane.showInputDialog(“Enter

Hours”);Hours”); JOptionPane.showMessageDialog(null, “Hello JOptionPane.showMessageDialog(null, “Hello

World”);World”); I/O Streams (java.io.*)I/O Streams (java.io.*)

BufferedReader br = new BufferedReader(new BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); InputStreamReader(System.in));

String s = br.readLine();String s = br.readLine(); java.util.Scannerjava.util.Scanner(( JDK 1.5 or aboveJDK 1.5 or above ))

Scanner reader = new Scanner(System.in);Scanner reader = new Scanner(System.in); int h = reader.nextInt();int h = reader.nextInt();

這種將類別分成三個主要種類的模式,我們稱之這種將類別分成三個主要種類的模式,我們稱之為 為 MVCMVC (Model, View, and Control) Model. (Model, View, and Control) Model.

11

Instances vs. ClassesInstances vs. Classes Constructor (Constructor ( 建構元建構元 )) hourly rate, 1.5, and 2 hourly rate, 1.5, and 2 怎麼辦?怎麼辦?

instance datainstance data class dataclass data (加上 (加上 staticstatic )) 其差別在於其差別在於

記憶體的考量記憶體的考量 instance data instance data 必須物件存在的時候,他才存在;而 必須物件存在的時候,他才存在;而

class data class data 是 是 class class 存在的時候,他就存在了。存在的時候,他就存在了。 類似的情形也存在於 類似的情形也存在於 methodmethod

instance methodinstance method class method class method (加上 (加上 staticstatic ))

12

EncapsulationEncapsulation

物件導向模式的第一個特性 物件導向模式的第一個特性 -- -- EncapsulationEncapsulation ((封裝封裝)) 為什麼要 為什麼要 encapsulationencapsulation ?? Java Java 如何完成 如何完成 encapsulationencapsulation ??

publicpublic privateprivate protectedprotected nonenone

看一下 看一下 UML UML 的 的 Class Class 以及 以及 Object Object 的圖的圖

13

An ExerciseAn Exercise 範例範例A company has four salespeople who sell five A company has four salespeople who sell five

different products. Once a day, each different products. Once a day, each salesperson passes in a slip for each different salesperson passes in a slip for each different type of product sold. Each slip containstype of product sold. Each slip contains the salesperson number (1 to 4), the salesperson number (1 to 4), the product number (1 to 5), andthe product number (1 to 5), and the total dollar value of that product sold that day.the total dollar value of that product sold that day.

Thus, each salesperson passes in between 0 Thus, each salesperson passes in between 0 and 5 sales slips per day. Please write an OO and 5 sales slips per day. Please write an OO program (not applet) that will read all program (not applet) that will read all information and summarize the total sales by information and summarize the total sales by salesperson.salesperson.

14

DiscussionsDiscussions

討論的主題討論的主題 有哪些 有哪些 Model classesModel classes ??

陣列 陣列 vs. Vectorvs. Vector 為什麼 為什麼 Vector Vector 的元素可以包含我們建立的 的元素可以包含我們建立的 classesclasses ?想想?想想

看一個物件有時候它是某個資料型態,在另一個時候它又是另看一個物件有時候它是某個資料型態,在另一個時候它又是另一個資料型態。這種特色稱之為一個資料型態。這種特色稱之為多型多型(( PolymorphismPolymorphism ),),而要了解多型,就必須先知道而要了解多型,就必須先知道繼承繼承(( InheritanceInheritance )。)。

EncapsulationEncapsulation、、 InheritanceInheritance 、以及 、以及 Polymorphism Polymorphism 合稱物件導向模式的三大特色合稱物件導向模式的三大特色 注意,有非常多的專家學者強調不要為了符合這三大注意,有非常多的專家學者強調不要為了符合這三大

特色而犧牲了 特色而犧牲了 reusability reusability 和 和 maintainability maintainability

15

InheritanceInheritance

16

InheritanceInheritance

Superclasses vs. subclassesSuperclasses vs. subclasses base classes vs. derived classesbase classes vs. derived classes

子類別的物件自動繼承父類別的特性(包含屬性子類別的物件自動繼承父類別的特性(包含屬性以及行為)以及行為) protected, private, and publicprotected, private, and public (避免把問題複雜(避免把問題複雜

化了,自己去了解 化了,自己去了解 none none 在繼承架構所扮演的角色)在繼承架構所扮演的角色) 產生繼承架構的方式產生繼承架構的方式

specializationspecialization generalizationgeneralization

17

ExampleExample 常見的範例:圓形以及矩形。常見的範例:圓形以及矩形。

如何定義一個圓形、矩形。如何定義一個圓形、矩形。

18

ExampleExamplepublic class Point { public class Point { protected int x, y; // coordinates of the protected int x, y; // coordinates of the

Point Point public Point() { setPoint( 0, 0 ); } public Point() { setPoint( 0, 0 ); } public Point( int a, int b ) { setPoint( a, b ); public Point( int a, int b ) { setPoint( a, b );

} } public void setPoint( int a, int b ) { x = a; y public void setPoint( int a, int b ) { x = a; y

= b; }= b; } public int getX() { return x; } public int getX() { return x; } public int getY() { return y; } public int getY() { return y; } public String toString() { public String toString() { return "[" + x + ", " + y + "]"; } return "[" + x + ", " + y + "]"; } } }

19

ExampleExamplepublic class Circle extends Point { public class Circle extends Point { protected double radius; protected double radius; public Circle() { public Circle() { // implicitly call superclass's constructor occurs here // implicitly call superclass's constructor occurs here setRadius( 0 ); } setRadius( 0 ); } public Circle( double r, int a, int b ) { super( a, b ); public Circle( double r, int a, int b ) { super( a, b );

setRadius( r ); } setRadius( r ); } public void setRadius( double r ) { radius = ( r >= 0.0 ? r : public void setRadius( double r ) { radius = ( r >= 0.0 ? r :

0.0 ); } 0.0 ); } public double getRadius() { return radius; } public double getRadius() { return radius; } // // 新增:新增: Calculate area of Circle Calculate area of Circle public double area() { return Math.PI * radius * radius; } public double area() { return Math.PI * radius * radius; } // 1. // 1. 改寫:改寫: convert the Circle to a String convert the Circle to a String // 2. // 2. 存取 存取 Point Point 內的屬性 內的屬性 x x 與 與 y y 就跟存取自己的屬性一樣就跟存取自己的屬性一樣 // 3. // 3. 稱為 稱為 overriding overriding public String toString() { return "Center = " + "[" + x + ", " public String toString() { return "Center = " + "[" + x + ", "

+ y + "]" + "; Radius = " + radius; } + y + "]" + "; Radius = " + radius; } } }

20

ExampleExample

請你為一家公司設計一套人事資訊系統,請你為一家公司設計一套人事資訊系統,這套系統要能夠讓人事室的員工隨時新增、這套系統要能夠讓人事室的員工隨時新增、刪除、修改、以及查詢員工資料。刪除、修改、以及查詢員工資料。 首先,討論我們需要記錄員工的哪些資料首先,討論我們需要記錄員工的哪些資料 經仔細的討論後,我們發現員工分成兩類 經仔細的討論後,我們發現員工分成兩類 -- -- 領固定薪資的員工以及依照工作時數的員工領固定薪資的員工以及依照工作時數的員工(當然還有可能是領取營業績效的員工)。(當然還有可能是領取營業績效的員工)。

請以 請以 specialization specialization 以及 以及 generalization generalization 的方式來完成繼承架構。的方式來完成繼承架構。

21

InheritanceInheritance Inheritance Inheritance is-a relationship is-a relationship Aggregation Aggregation has-a (or part of) has-a (or part of)

relationshiprelationship An employee has a birthdateAn employee has a birthdateclass Employee {class Employee { String name;String name; Date birthdate;Date birthdate;}} The relationships between Shape, Point, Circle, The relationships between Shape, Point, Circle,

and Rectangle.and Rectangle. Inheritance vs. AggregationInheritance vs. Aggregation

to be discussed later.to be discussed later. conclusions: use them wisely.conclusions: use them wisely.

22

ExerciseExercise

範例範例Imagine a publishing company that markets both Imagine a publishing company that markets both

books and CDs. This company asked you to books and CDs. This company asked you to write a program to display their products write a program to display their products properly on the Web. After studying their properly on the Web. After studying their requirements, you found out the information requirements, you found out the information required for books includes book title, price, required for books includes book title, price, author name, and page numbers. The author name, and page numbers. The information required for CDs are CD title, information required for CDs are CD title, price, singer's name, and playing time. Please price, singer's name, and playing time. Please design an appropriate inheritance hierarchy for design an appropriate inheritance hierarchy for this program.this program.

23

Upcast and Dynamic Upcast and Dynamic BindingBinding

假設我們有一個繼承架構,其根節點為「人」,假設我們有一個繼承架構,其根節點為「人」,而其子節點為「白種人」、 「黃種人」、和「黑而其子節點為「白種人」、 「黃種人」、和「黑種人」。 由於每一個子類別的物件同時也是一個種人」。 由於每一個子類別的物件同時也是一個父類別的物件(如每一個黃種人都是 人,但是每父類別的物件(如每一個黃種人都是 人,但是每一個人卻不一定是黃種人),所以 一個人卻不一定是黃種人),所以 Java Java 允許子允許子類別的物件 類別的物件 upcast upcast 到父類別的物件。 到父類別的物件。

Connecting a method call to a method body is Connecting a method call to a method body is called called bindingbinding. When binding is performed . When binding is performed before the program run, it's called before the program run, it's called early bindingearly binding or or static bindingstatic binding. When the binding occurs at . When the binding occurs at run-time, we call it run-time, we call it late bindinglate binding, , dynamic dynamic bindingbinding, or , or run-time bindingrun-time binding. .

24

Upcast and Dynamic Upcast and Dynamic BindingBinding

VectorVector Vector Vector 的元素都是 的元素都是 ObjectObject ,而 ,而 Object Object 是是

所有 所有 Java Java 類別的父類別(或者稱之為祖先類類別的父類別(或者稱之為祖先類別)別)

利用 利用 Worker Worker 以及 以及 Vector Vector 來產生 來產生 WorkerRecord.WorkerRecord.

25

Upcast and Dynamic Upcast and Dynamic BindingBindingimport java.util.*;import java.util.*;

public class WorkerRecord {public class WorkerRecord { //private Vector<Worker> records = //private Vector<Worker> records = // new Vector<Worker>();// new Vector<Worker>(); private Vector records = new Vector();private Vector records = new Vector();

public WorkerRecord() {}public WorkerRecord() {} public WorkerRecord(Worker w) {public WorkerRecord(Worker w) { records.add(w);records.add(w); }}

public void setRecords(Worker w) {public void setRecords(Worker w) { records.add(w);records.add(w); }} public Worker getRecords(int idx) {public Worker getRecords(int idx) { if (idx < records.size())if (idx < records.size()) return (Worker) return (Worker)

records.elementAt(idx);records.elementAt(idx); elseelse return null;return null; }}

public double getSalary(int idx) {public double getSalary(int idx) { if (idx < records.size())if (idx < records.size()) return ((Worker) return ((Worker) records.get(idx)).calcSalary();records.get(idx)).calcSalary(); elseelse return -1.0;return -1.0; }}

public static void main(String[] args) public static void main(String[] args) {{ WorkerRecord r = new WorkerRecord r = new WorkerRecord(new Worker(40));WorkerRecord(new Worker(40)); r.setRecords(new Worker(65));r.setRecords(new Worker(65));

System.out.println(r.getSalary(0));System.out.println(r.getSalary(0)); System.out.println(r.getSalary(1));System.out.println(r.getSalary(1)); }}}}

26

ExampleExampleimport java.text.DecimalFormat; import java.text.DecimalFormat; import javax.swing.JOptionPane; import javax.swing.JOptionPane; public class UpCasting { public class UpCasting { public static void main( String args[] ) { public static void main( String args[] ) { Point pointRef, p; Point pointRef, p; Circle circleRef, c; Circle circleRef, c; String output; String output;

p = new Point( 30, 50 ); p = new Point( 30, 50 ); c = new Circle( 2.7, 120, 89 ); c = new Circle( 2.7, 120, 89 ); output = "Point p: " + p.toString() + "\nCircle c: " + c.toString(); output = "Point p: " + p.toString() + "\nCircle c: " + c.toString();

// upcasting: use the "is a" relationship to refer to a // upcasting: use the "is a" relationship to refer to a // Circle with a Point reference // Circle with a Point reference pointRef = c; // assign Circle to pointRef pointRef = c; // assign Circle to pointRef

// upcasting // upcasting 之後要注意的是你能用的 之後要注意的是你能用的 methods methods 都只是 都只是 // base class // base class 內定義過的,否則會 內定義過的,否則會 compilation error compilation error //output += "\nCircle c (via pointRef): " + pointRef.area(); //output += "\nCircle c (via pointRef): " + pointRef.area();

27

ExampleExample // // 非常有意思的是這個 非常有意思的是這個 toString() toString() 呼叫的是 呼叫的是 Circle Circle

的 的 // toString() // toString() 而不是 而不是 Point Point 的 的 toString()toString() 。 。 output += "\n\nCircle c (via pointRef): " + output += "\n\nCircle c (via pointRef): " +

pointRef.toString(); pointRef.toString();

// // 有意思的是經過 有意思的是經過 upcastingupcasting ,雖然 ,雖然 pointRef pointRef 是 是 PointPoint , ,

// // 但是卻可以檢測出其實他代表一個 但是卻可以檢測出其實他代表一個 Circle Circle 的物件 的物件 if (pointRef instanceof Circle) if (pointRef instanceof Circle) output += "\npointRef is an instance of Circle"; output += "\npointRef is an instance of Circle"; else else output += "\npointRef is NOT an instance of output += "\npointRef is NOT an instance of

Circle"; Circle";

28

ExampleExample // Use downcasting (casting a superclass reference to a // Use downcasting (casting a superclass reference to a // subclass data type) to assign pointRef to circleRef // subclass data type) to assign pointRef to circleRef circleRef = (Circle) pointRef; circleRef = (Circle) pointRef; output += "\n\nCircle c (via circleRef): " + circleRef.toString();output += "\n\nCircle c (via circleRef): " + circleRef.toString(); DecimalFormat precision2 = new DecimalFormat( "0.00" );DecimalFormat precision2 = new DecimalFormat( "0.00" ); output += "\nArea of c (via circleRef): " + output += "\nArea of c (via circleRef): " +

precision2.format( circleRef.area() ); precision2.format( circleRef.area() );

// Attempt to refer to Point object // Attempt to refer to Point object // with Circle reference // with Circle reference // // 下面這個敘述不可以,因為「不是所有的人都是黃種人」 下面這個敘述不可以,因為「不是所有的人都是黃種人」 // for details, please refer to "downcasting". // for details, please refer to "downcasting". //circleRef = (Circle) p; //circleRef = (Circle) p; JOptionPane.showMessageDialog( null, output, JOptionPane.showMessageDialog( null, output, "Demonstrating the \"is a\" "Demonstrating the \"is a\"

relationship",relationship",

JOptionPane.INFORMATION_MESSAGE ); JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); System.exit( 0 ); } } } }

29

Upcast and Dynamic Upcast and Dynamic BindingBinding

從之前的範例,我們清楚的知道,如果從之前的範例,我們清楚的知道,如果要善用 要善用 dynamic bindingdynamic binding ,子類別,子類別中的方法最好也在父類別中定義,如此中的方法最好也在父類別中定義,如此一來,當我們呼叫一個物件行為的時候,一來,當我們呼叫一個物件行為的時候,可以由系統自動的依照物件的真正型態可以由系統自動的依照物件的真正型態來 來 binding binding 到正確的方法到正確的方法 以 以 Circle Circle 以及 以及 Rectangle Rectangle 為例為例 以人事系統為例以人事系統為例

30

Upcast and Dynamic Upcast and Dynamic BindingBinding

在把之前的人事系統為例,假設我們要求寫一個在把之前的人事系統為例,假設我們要求寫一個程式,使得使用者可以輸入 程式,使得使用者可以輸入 10 10 個員工,而這十個員工,而這十個員工有些是 個員工有些是 SalaryEmployeeSalaryEmployee ,有些是 ,有些是 HourlyEmployeeHourlyEmployee ,可以事先我們不知道他們,可以事先我們不知道他們各別是多少個,使用者又不知道將來可能會輸入各別是多少個,使用者又不知道將來可能會輸入的順序的順序 這個類似快打旋風中,程式無法事先知道使用者會選用哪一個角這個類似快打旋風中,程式無法事先知道使用者會選用哪一個角

色色 解法(概念)解法(概念)

我們都知道 我們都知道 SalaryEmployee SalaryEmployee 和 和 HourlyEmployee HourlyEmployee 都是 都是 EmployeeEmployee(( upcast upcast 可以完成),所以可以完成),所以……

而我們設計的時候,又可以善用 而我們設計的時候,又可以善用 dynamic bindingdynamic binding 重要結論:重要結論: Employee Employee 物件有時候是 物件有時候是 EmployeeEmployee ,有時候是 ,有時候是

SalaryEmployeeSalaryEmployee ,有時候又是 ,有時候又是 HourlyEmployeeHourlyEmployee ,這就是多,這就是多型的概念。型的概念。

31

PolymorphismPolymorphism 一個物件(如 一個物件(如 employees[i]employees[i] )可以擁有一)可以擁有一

種以上的「面像」種以上的「面像」 (forms)(forms) ,而且「面像」 ,而且「面像」 之間又有一定的關係(這個關係就是能夠使之間又有一定的關係(這個關係就是能夠使用多型的物件其資料型態必須是所有可能 出用多型的物件其資料型態必須是所有可能 出現的面像的父類別),這就是「現的面像的父類別),這就是「多型多型」的由」的由來。 來。

PolymorphismPolymorphism means you can use a means you can use a variable of a superclass type to hold a variable of a superclass type to hold a reference to an object whose class is reference to an object whose class is the superclass or any of its subclasses.the superclass or any of its subclasses.

32

ExerciseExercise

範例範例Continue from the previous example. Continue from the previous example.

Please finish a POS (Point-Of-Sale) Please finish a POS (Point-Of-Sale) program that will print out the list of program that will print out the list of sold items and calculate the total sold items and calculate the total amount of the sold items.amount of the sold items.

33

InheritanceInheritance

Single Inheritance vs. Multiple InheritanceSingle Inheritance vs. Multiple Inheritance A Famous Problem A Famous Problem Diamond ProblemDiamond Problem

侏儸紀公園的年代侏儸紀公園的年代

34

InheritanceInheritanceabstract class Animal { abstract class Animal { abstract void talk(); abstract void talk(); } } class Frog extends Animal { class Frog extends Animal { void talk() { System.out.println("Ribit, ribit."); } void talk() { System.out.println("Ribit, ribit."); } } } class Dinosaur extends Animal { class Dinosaur extends Animal { void talk() { System.out.println("Oh I'm a dinosaur and I'm void talk() { System.out.println("Oh I'm a dinosaur and I'm

OK..."); } OK..."); } } } // // 要特別注意的是 要特別注意的是 Java Java 並不支援多重繼承。所以這段程式只是 並不支援多重繼承。所以這段程式只是 // // 用來說明 用來說明 diamond problem diamond problem 的概念 的概念 class Frogosaur extends Frog, Dinosaur { } class Frogosaur extends Frog, Dinosaur { } --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

------現在如果某個程式做了下列的宣告, 現在如果某個程式做了下列的宣告, Animal animal = new Frogosaur(); Animal animal = new Frogosaur(); animal.talk(); animal.talk(); 那麼問題就來了,這隻 那麼問題就來了,這隻 Frogosaur Frogosaur 究竟要發出哪一種聲音呢? 究竟要發出哪一種聲音呢?