43
1 繼繼 繼繼 (Inheritance) (Inheritance) 鄭鄭鄭 鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 / / 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭鄭 / / 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭

繼承 (Inheritance)

Embed Size (px)

DESCRIPTION

繼承 (Inheritance). 鄭士康 國立台灣大學 電機工程學系 / 電信工程研究所 / 資訊網路與多媒體研究所. UsingInheritance.Program (1/7). using System; namespace UsingInheritance { /* * 示範繼承的使用 * 4/23/2007 */ class Program { static void Main(string[] args) { - PowerPoint PPT Presentation

Citation preview

Page 1: 繼承 (Inheritance)

1

繼承繼承(Inheritance)(Inheritance)

鄭士康鄭士康國立台灣大學國立台灣大學

電機工程學系電機工程學系 // 電信工程研究所電信工程研究所 //資訊網路與多媒體研究所資訊網路與多媒體研究所

Page 2: 繼承 (Inheritance)

2

UsingInheritance.Program UsingInheritance.Program (1/7)(1/7)

using System;using System;

namespace UsingInheritancenamespace UsingInheritance{{ /* /* * * 示範繼承的使用示範繼承的使用 * 4/23/2007* 4/23/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ AdvancedCalculator calculator = new AdvancedCalculator calculator = new

AdvancedCalculator();AdvancedCalculator();

Page 3: 繼承 (Inheritance)

3

UsingInheritance.Program UsingInheritance.Program (2/7)(2/7)

int op = 0;int op = 0; int operand1 = 0;int operand1 = 0; int operand2 = 0;int operand2 = 0; int result;int result; double angle = 0.0;double angle = 0.0; double functionValue;double functionValue; dodo {{ Console.Write(Console.Write( ""指定運算指定運算 : 0. : 0. 結束結束 ; 1. ; 1. 加加 ; 2. ; 2. 減減 ; 3. ; 3. 乘乘 ; 4. ; 4. 除除 ; " ; "

++ " \n 5. " \n 5. 正弦函數正弦函數 ; 6. ; 6. 餘弦函數餘弦函數 ; 7. ; 7. 正切函數正切函數 : : ");");

op = int.Parse(Console.ReadLine());op = int.Parse(Console.ReadLine()); if (op == 0) break;if (op == 0) break; if (op > 7) continue;if (op > 7) continue;

Page 4: 繼承 (Inheritance)

4

UsingInheritance.Program UsingInheritance.Program (3/7)(3/7)

if (op < 5)if (op < 5) {{ Console.Write("Console.Write("輸入第一個數字輸入第一個數字 : ");: "); operand1 = int.Parse(Console.ReadLine());operand1 = int.Parse(Console.ReadLine()); Console.Write("Console.Write("輸入第二個數字輸入第二個數字 : ");: "); operand2 = int.Parse(Console.ReadLine());operand2 = int.Parse(Console.ReadLine()); }} elseelse {{ Console.Write("Console.Write("輸入角度輸入角度 ((度度 )");)"); angle = double.Parse(Console.ReadLine());angle = double.Parse(Console.ReadLine()); }} switch (op)switch (op) {{

Page 5: 繼承 (Inheritance)

5

UsingInheritance.Program UsingInheritance.Program (4/7)(4/7)

case 1:case 1: result = calculator.Add(operand1,result = calculator.Add(operand1, operand2);operand2); Console.WriteLine("{0} + {1} = {2} ",Console.WriteLine("{0} + {1} = {2} ", operand1, operand2, result);operand1, operand2, result); break;break; case 2:case 2: result = calculator.Subtract(operand1,result = calculator.Subtract(operand1, operand2);operand2); Console.WriteLine("{0} - {1} = {2} ",Console.WriteLine("{0} - {1} = {2} ", operand1, operand2, result);operand1, operand2, result); break;break; case 3:case 3: result = calculator.Multiply(operand1,result = calculator.Multiply(operand1, operand2);operand2);

Page 6: 繼承 (Inheritance)

6

UsingInheritance.Program UsingInheritance.Program (5/7)(5/7)

Console.WriteLine("{0} * {1} = {2} ",Console.WriteLine("{0} * {1} = {2} ", operand1, operand2, result);operand1, operand2, result); break;break; case 4:case 4: result = calculator.Divide(operand1,result = calculator.Divide(operand1, operand2);operand2); Console.WriteLine("{0} / {1} = {2} ",Console.WriteLine("{0} / {1} = {2} ", operand1, operand2, result);operand1, operand2, result); break; break; case 5:case 5: functionValue = functionValue =

calculator.getSine(angle);calculator.getSine(angle); Console.WriteLine(Console.WriteLine(

"Sine of {0} (deg) = {1}","Sine of {0} (deg) = {1}", angle, functionValue);angle, functionValue); break;break;

Page 7: 繼承 (Inheritance)

7

UsingInheritance.Program UsingInheritance.Program (6/7)(6/7)

case 6:case 6: functionValue = functionValue =

calculator.getCosine(angle);calculator.getCosine(angle); Console.WriteLine(Console.WriteLine(

"Cosine of {0} (deg) = {1}","Cosine of {0} (deg) = {1}", angle, functionValue);angle, functionValue); break;break; case 7:case 7: functionValue = functionValue =

calculator.getTangent(angle);calculator.getTangent(angle); Console.WriteLine(Console.WriteLine(

"Tangent of {0} (deg) = {1}","Tangent of {0} (deg) = {1}", angle, functionValue);angle, functionValue); break;break;

Page 8: 繼承 (Inheritance)

8

UsingInheritance.Program UsingInheritance.Program (7/7)(7/7)

default:default: Console.WriteLine(Console.WriteLine( "Should not see this message. "Should not see this message.

Debug!!!");Debug!!!"); break;break; }} } while (true);} while (true); }} }}}}

Page 9: 繼承 (Inheritance)

9

UsingInheritance.AdvancedCalculUsingInheritance.AdvancedCalculator (1/2)ator (1/2)

using System;using System;

namespace UsingInheritancenamespace UsingInheritance{{ /*/* * * 可計算三角函數之計算器可計算三角函數之計算器 * 4/23/2007* 4/23/2007 */*/ public public class AdvancedCalculator : Calculatorclass AdvancedCalculator : Calculator {{ public double getSine( double angle ) public double getSine( double angle ) {{ angle *= Math.PI/180.0;angle *= Math.PI/180.0; return Math.Sin(angle);return Math.Sin(angle); }}

Page 10: 繼承 (Inheritance)

10

UsingInheritance.AdvancedCalculUsingInheritance.AdvancedCalculator (2/2)ator (2/2)

public double getCosine( double angle )public double getCosine( double angle ) {{ angle *= Math.PI/180.0;angle *= Math.PI/180.0; return Math.Cos(angle);return Math.Cos(angle); }} public double getTangent( double angle )public double getTangent( double angle ) {{ angle *= Math.PI/180.0;angle *= Math.PI/180.0; return Math.Tan(angle);return Math.Tan(angle); }} }}}}

Page 11: 繼承 (Inheritance)

11

UsingInheritance.Calculator (1UsingInheritance.Calculator (1/2)/2)

using System;using System;

namespace UsingInheritancenamespace UsingInheritance{{ /*/* * * 計算器計算器 * 3/17/2007* 3/17/2007 */*/ class Calculatorclass Calculator {{ public int Add(int a, int b)public int Add(int a, int b) {{ int result = a + b;int result = a + b; return result;return result; }}

Page 12: 繼承 (Inheritance)

12

UsingInheritance.Calculator (2UsingInheritance.Calculator (2/2)/2)

public int Subtract(int a, int b)public int Subtract(int a, int b) {{ int result = a - b;int result = a - b; return result;return result; }} public int Multiply(int a, int b)public int Multiply(int a, int b) {{ int result = a * b;int result = a * b; return result;return result; }} public int Divide(int a, int b)public int Divide(int a, int b) {{ int result = a / b;int result = a / b; return result;return result; }} }}}}

Page 13: 繼承 (Inheritance)

13

表示繼承的表示繼承的 UMLUML 類別圖類別圖Calculator

Add()Subtraction()Multiply()Divide()

AdvancedCalculator

getSine()getCosine()getTangent()

Page 14: 繼承 (Inheritance)

14

類別繼承之階層關係類別繼承之階層關係class A {class A {

public int data1;public int data1;public int data2; public int data2; //…other members are methods//…other members are methods

};};

class B : public A {class B : public A {public int data3;public int data3;

//…other members are methods//…other members are methods};};

class C : public B {class C : public B {public int data1;public int data1;public int data4;public int data4;

//…other members are methods//…other members are methods};};

A

B

C

Page 15: 繼承 (Inheritance)

15

物件記憶體分配模型物件記憶體分配模型A a;A a;

B b;B b;

C c;C c;

data1

data2

data1

data2

data3

a

b

A.data1

data2

data3

data1

data4

c

Page 16: 繼承 (Inheritance)

16

UsingProtected.Program (1/UsingProtected.Program (1/2)2)

using System;using System;namespace UsingProtectednamespace UsingProtected{{ /* /* 示範示範 protectedprotected成員之使用成員之使用 * 4/23/2007* 4/23/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ DC d = new DC();DC d = new DC(); d.setX(3);d.setX(3); //Console.WriteLine( d.getX() ) ; // Error!//Console.WriteLine( d.getX() ) ; // Error! // d.x = 77; // Error!// d.x = 77; // Error! d.add2();d.add2(); }} }}

Page 17: 繼承 (Inheritance)

17

UsingProtected.Program (2/UsingProtected.Program (2/2)2)

public class BC public class BC {{ public void setX( int x ) { this.x = x; }public void setX( int x ) { this.x = x; } protected int getX() { return x; }protected int getX() { return x; } private int x;private int x; }}

public class DC : BC public class DC : BC {{ public void add2() public void add2() {{

int c = getX();int c = getX(); setX( c+2 ); setX( c+2 );

} } }}}}

Page 18: 繼承 (Inheritance)

18

限制繼承限制繼承sealed class SClass sealed class SClass

{{

. . . . . .. . . . . .

}}

Page 19: 繼承 (Inheritance)

19

物件導向的關鍵技術物件導向的關鍵技術• 封裝封裝 (packaging)(packaging)• 繼承繼承 (inheritance)(inheritance)• 多型多型 (polymorphism)(polymorphism)

Page 20: 繼承 (Inheritance)

20

多型多型• 編譯時連結編譯時連結 (compile-time binding)(compile-time binding) 與執與執

行時連結行時連結 (run-time binding)(run-time binding)– 靜態連結靜態連結 (static binding)(static binding) 與動態連結與動態連結 (dyna(dyna

mic binding)mic binding)• 多型之要求多型之要求

– 繼承階層體系繼承階層體系– 虛擬虛擬 (virtual)(virtual) 與覆寫與覆寫 (override)(override)– 基礎類別之參考基礎類別之參考

• 多型之優缺點多型之優缺點

Page 21: 繼承 (Inheritance)

21

UsingOverride.Program (1/UsingOverride.Program (1/3)3)

using System;using System;namespace UsingOverridenamespace UsingOverride{{

/* /* 示範方法函式之覆寫示範方法函式之覆寫 (overriding)(overriding)與多型與多型 * 5/2/2007* 5/2/2007

*/*/

class Programclass Program

{{

static void Main(string[] args)static void Main(string[] args)

{ {

Console.WriteLine(Console.WriteLine(

""選擇列印尺寸規格選擇列印尺寸規格 : 1. B4 ; 2. A3 ; : 1. B4 ; 2. A3 ; 其他其他 : : 標準標準(A4)");(A4)");

Page 22: 繼承 (Inheritance)

22

UsingOverride.Program (2/UsingOverride.Program (2/3)3) int reportType = int.Parse(Console.ReadLine());int reportType = int.Parse(Console.ReadLine());

Console.WriteLine();Console.WriteLine(); Printer pr;Printer pr; switch (reportType)switch (reportType) {{ case 1:case 1: pr = new PrinterB4();pr = new PrinterB4(); pr.Print();pr.Print(); break;break; case 2:case 2: pr = new PrinterA3();pr = new PrinterA3(); pr.Print();pr.Print(); break;break; default:default: pr = new Printer();pr = new Printer(); pr.Print();pr.Print(); break;break; }}

Page 23: 繼承 (Inheritance)

23

UsingOverride.Program (3/UsingOverride.Program (3/3)3)

Console.WriteLine();Console.WriteLine();

Console.ReadLine();Console.ReadLine();

}}

Page 24: 繼承 (Inheritance)

24

UsingOverride.Printer (1/2)UsingOverride.Printer (1/2)using System;using System;namespace UsingOverridenamespace UsingOverride{{ /*/* * * 模擬標準印表機模擬標準印表機 * 5/1/2007* 5/1/2007 */*/ class Printerclass Printer {{ public Printer()public Printer() {{ Console.WriteLine("Console.WriteLine("印表機備便印表機備便 ");"); }} virtual public void Print()virtual public void Print() {{ Console.WriteLine("Console.WriteLine("列印標準尺寸列印標準尺寸 ");"); Finish("Finish("標準標準 ");"); }}

Printer

Print()

Page 25: 繼承 (Inheritance)

25

UsingOverride.Printer (2/2)UsingOverride.Printer (2/2) protected void Finish(string type)protected void Finish(string type)

{{

Console.WriteLine("{0}Console.WriteLine("{0}報表列印完成報表列印完成 ", type);", type);

}}

}}

}}

Page 26: 繼承 (Inheritance)

26

UsingOverride. PrinterB4UsingOverride. PrinterB4using System;using System;namespace UsingOverridenamespace UsingOverride {{ /*/* * * 模擬模擬 B4B4印表程式印表程式 * 5/1/2007* 5/1/2007 */*/ class PrinterB4 : Printerclass PrinterB4 : Printer {{ public PrinterB4()public PrinterB4() {{ Console.WriteLine("B4Console.WriteLine("B4尺寸列印程式備便尺寸列印程式備便 ");"); }} override public void Print()override public void Print() {{ Console.WriteLine("Console.WriteLine("列印列印 B4B4尺寸尺寸 ");"); Finish("B4");Finish("B4"); }} }}}}

Page 27: 繼承 (Inheritance)

27

UsingOverride. PrinterA3UsingOverride. PrinterA3using System;using System;namespace UsingOverridenamespace UsingOverride {{ /*/* * * 模擬模擬 A3A3印表程式印表程式 * 5/1/2007* 5/1/2007 */*/ class PrinterA3 : Printerclass PrinterA3 : Printer {{ public PrinterA3()public PrinterA3() {{ Console.WriteLine("A3Console.WriteLine("A3尺寸列印程式備便尺寸列印程式備便 ");"); }} override public void Print()override public void Print() {{ Console.WriteLine("Console.WriteLine("列印列印 A3A3尺寸尺寸 ");"); Finish("A3");Finish("A3"); }} }}}}

Page 28: 繼承 (Inheritance)

28

練習練習• 撰寫類別撰寫類別 ShapeShape ,定義虛擬方法,定義虛擬方法 DrawDraw 為為

輸出”畫形狀”字樣。其次撰寫類別輸出”畫形狀”字樣。其次撰寫類別 RectRectangleangle 及及 CircleCircle ,分別覆寫,分別覆寫 DrawDraw 為輸為輸出字串”畫長方形”及”畫圓形” 。寫一出字串”畫長方形”及”畫圓形” 。寫一程式測試此一繼承結構之多型機制。程式測試此一繼承結構之多型機制。

Page 29: 繼承 (Inheritance)

29

UsingBase.Program (1/6)UsingBase.Program (1/6)using System;using System;namespace UsingBasenamespace UsingBase{{ /* /* 示範示範 basebase與與 newnew關鍵字的用法關鍵字的用法 * Ref: C# * Ref: C# 程式設計人員參考 程式設計人員參考 * * 瞭解使用瞭解使用 Override Override 和和 New New 關鍵字的時機關鍵字的時機 (C# (C# 程式設計手冊程式設計手冊 ) ) * *

ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.cht/ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.cht/dv_csref/html/323db184-b136-46fc-8839-dv_csref/html/323db184-b136-46fc-8839-007886e7e8b0.htm007886e7e8b0.htm

* 5/2/2007* 5/2/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{

Page 30: 繼承 (Inheritance)

30

UsingBase.Program (2/6)UsingBase.Program (2/6)// new and override make no differences here// new and override make no differences here

Car car1 = new Car();Car car1 = new Car(); car1.DescribeCar();car1.DescribeCar(); System.Console.WriteLine("----------");System.Console.WriteLine("----------");

ConvertibleCar car2 = new ConvertibleCar();ConvertibleCar car2 = new ConvertibleCar(); car2.DescribeCar();car2.DescribeCar(); System.Console.WriteLine("----------");System.Console.WriteLine("----------");

Minivan car3 = new Minivan();Minivan car3 = new Minivan(); car3.DescribeCar();car3.DescribeCar(); System.Console.WriteLine("----------");System.Console.WriteLine("----------");

Page 31: 繼承 (Inheritance)

31

UsingBase.Program (3/6)UsingBase.Program (3/6)// they are different in polymorphysm // they are different in polymorphysm

Car[] cars = new Car[3];Car[] cars = new Car[3]; cars[0] = new Car();cars[0] = new Car(); cars[1] = new ConvertibleCar();cars[1] = new ConvertibleCar(); cars[2] = new Minivan();cars[2] = new Minivan(); foreach (Car vehicle in cars)foreach (Car vehicle in cars) {{ System.Console.WriteLine("Car object: " System.Console.WriteLine("Car object: "

+ vehicle.GetType());+ vehicle.GetType()); vehicle.DescribeCar();vehicle.DescribeCar(); System.Console.WriteLine("----------");System.Console.WriteLine("----------"); }} }} }}

Page 32: 繼承 (Inheritance)

32

UsingBase.Program (4/6)UsingBase.Program (4/6)// Define the base class// Define the base class

class Carclass Car {{ public virtual void DescribeCar()public virtual void DescribeCar() {{ System.Console.WriteLine(System.Console.WriteLine(

"Four wheels and an engine.");"Four wheels and an engine."); }} }}

Page 33: 繼承 (Inheritance)

33

UsingBase.Program (5/6)UsingBase.Program (5/6)// Define the derived classes// Define the derived classes

class ConvertibleCar : Carclass ConvertibleCar : Car {{ public new virtual void DescribeCar()public new virtual void DescribeCar() {{ base.DescribeCar();base.DescribeCar(); System.Console.WriteLine(System.Console.WriteLine(

"A roof that opens up.");"A roof that opens up."); }} }}

Page 34: 繼承 (Inheritance)

34

UsingBase.Program (6/6)UsingBase.Program (6/6)class Minivan : Carclass Minivan : Car

{{ public override void DescribeCar()public override void DescribeCar() {{ base.DescribeCar();base.DescribeCar(); System.Console.WriteLine(System.Console.WriteLine(

"Carries seven people.");"Carries seven people."); }} }}}}

Page 35: 繼承 (Inheritance)

35

覆寫與隱藏覆寫與隱藏• 覆寫覆寫 : : overrideoverride

– 主要用於主要用於 Polymorphism (Polymorphism ( 多型多型 ))– 執行時連結執行時連結

• 隱藏隱藏 : : newnew– 只是取代基底類別同名之成員變數與方法只是取代基底類別同名之成員變數與方法– 仍是編譯時連結仍是編譯時連結

Page 36: 繼承 (Inheritance)

36

UsingConstructorsForInheritance.Program UsingConstructorsForInheritance.Program (1/4)(1/4)

using System;using System;namespace UsingConstructorsForInheritancenamespace UsingConstructorsForInheritance {{ /*/* * * 示範繼承架構中的建構式呼叫示範繼承架構中的建構式呼叫 * 5/2/2007* 5/2/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Animal slug = new Animal();Animal slug = new Animal();

Animal tweety = new Animal( "canary" );Animal tweety = new Animal( "canary" ); Primate godzilla = new Primate();Primate godzilla = new Primate(); Primate human = new Primate( 4 );Primate human = new Primate( 4 ); Human jill = new Human();Human jill = new Human();

Console.ReadLine();Console.ReadLine(); }} }}

Page 37: 繼承 (Inheritance)

37

UsingConstructorsForInheritance.Program UsingConstructorsForInheritance.Program (2/4)(2/4)

class Animal class Animal {{ public Animal() public Animal() {{

Console.WriteLine("Animal()"); Console.WriteLine("Animal()"); species = "Animal";species = "Animal";

}} public Animal( string s ) public Animal( string s )

{ { Console.WriteLine("Animal("+ s +")");Console.WriteLine("Animal("+ s +")"); species = s; species = s;

}} private string species;private string species; }}

Page 38: 繼承 (Inheritance)

38

UsingConstructorsForInheritance.Program UsingConstructorsForInheritance.Program (3/4)(3/4)

class Primate : Animal class Primate : Animal {{ public Primate() : base() public Primate() : base() {{

Console.WriteLine( "Primate()" );Console.WriteLine( "Primate()" ); }} public Primate( int n ) : base( "Primate" ) public Primate( int n ) : base( "Primate" )

{{ Console.WriteLine("Primate(" + n +")");Console.WriteLine("Primate(" + n +")"); heartCham = n;heartCham = n;

}} private int heartCham;private int heartCham; }}

Page 39: 繼承 (Inheritance)

39

UsingConstructorsForInheritance.Program UsingConstructorsForInheritance.Program (4/4)(4/4)

class Human : Primate class Human : Primate

{{

public Human() : base( 4 ) public Human() : base( 4 )

{{

Console.WriteLine( "Human()" );Console.WriteLine( "Human()" );

}}

}}

}}

Page 40: 繼承 (Inheritance)

40

預設類別預設類別 System.ObjectSystem.Object• 一致化型別一致化型別• 成員函式成員函式

– EqualsEquals– GetHashCodeGetHashCode– GetTypeGetType– ReferenceEqualsReferenceEquals– ToStringToString– FinalizeFinalize

Page 41: 繼承 (Inheritance)

41

InheritingObject.Program InheritingObject.Program (1/2)(1/2)

using System;using System;namespace InheritingObjectnamespace InheritingObject {{ /*/* * * 示範示範 ObjectObject類別類別 * 5/2/2007* 5/2/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Test t1 = new Test();Test t1 = new Test(); Test t2 = new Test();Test t2 = new Test(); bool isEqual = t1.Equals(t2);bool isEqual = t1.Equals(t2); Console.WriteLine(t1.ToString());Console.WriteLine(t1.ToString()); Console.WriteLine("t1 Console.WriteLine("t1 與與 t2 t2 相等為相等為 " + isEqual);" + isEqual); Console.ReadLine();Console.ReadLine(); }} }}

Page 42: 繼承 (Inheritance)

42

InheritingObject.Program InheritingObject.Program (2/2)(2/2)

class Testclass Test

{{

override public string ToString()override public string ToString()

{{

return "return "覆寫覆寫 InheritingObject.Test";InheritingObject.Test";

}}

}}

}}

Page 43: 繼承 (Inheritance)

43

Boxing Boxing 與 與 UnboxingUnboxingint x = 10;int x = 10;

Object obj = (Object) x;Object obj = (Object) x; // boxing // boxing

obj = 20;obj = 20;

int j = (int)obj;int j = (int)obj; // unboxing // unboxing