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. 自己想出一个练习