BOO入門/多型與繼承

BOO入門 > 多型與繼承 (上一章:方法 下一章:結構)


原標題:Polymorphism, or Inherited Methods

定義 定義 多型:讓衍生類別以新的方法來實作父類別既有的功能。

要能達到多型,主要使用兩個關鍵字:virtual 與 override。

如果你想讓衍生類別能覆寫、擴充方法的話,你需要在方法前面加上 virtual。

//  Rectangle  Square 為示範的多型範例
class Rectangle:
    def constructor(width as single, height as single):
        _width = width
        _height = height

    virtual def GetArea():
        return _width * _height
    
    _width as single
    _height as single

class Square(Rectangle):
    def constructor(width as single):
        _width = width

    override def GetArea():
        return _width * _width

r = Rectangle(4.0, 6.0)
s = Square(5.0)

print r.GetArea()
print s.GetArea()
print cast(Rectangle, s).GetArea()

輸出結果

24.0
25.0
25.0

即使將 s 轉型為 Rectangle,s.GetArea() 仍執行 Square.GetArea()。

// 簡化版的多型範例
class Base:
    virtual def Execute():
        print 'From Base'

class Derived(Base):
    override def Execute():
        print 'From Derived'

b = Base()
d = Derived()

b.Execute()
d.Execute()
cast(Base, d).Execute()

輸出結果

From Base
From Derived
From Derived

如果省略了 virtual 與 override 關鍵字的話,結果會是:

From Base
From Derived
From Base

當父類別的方法未加上 virtual 或 abstract 時,衍生類別的方法無法宣告為 override。

建議 建議 在繼承一個 virtual 方法時,即使你不需要明確地將方法宣告為 override(Boo 會自動加上),你最好還是加上,避免 virtual 方法與 override 方法標記未對應的情況發生。

要能被 override,父類別的方法必須宣告為 virtual 或 abstract,回傳的型別與引數也要一致。

當處理從同樣類別繼承下來的類別時,多型非常有用。

// 另一個多型範例
interface IAnimal:
    def MakeNoise()

class Dog(IAnimal):
    def MakeNoise():
        print 'Woof'

class Cat(IAnimal):
    def MakeNoise():
        print 'Meow'

class Hippo(IAnimal):
    def MakeNoise():
        print '*Noise of a Hippo*'

list = []
list.Add(Dog())
list.Add(Cat())
list.Add(Hippo())

for animal as IAnimal in list:
    list.MakeNoise()

輸出結果

Woof
Meow
*Noise of a Hippo*

練習 編輯

  1. 自己想出一個練習