# BOO入門/多型與繼承

（重定向自BOO/多型與繼承

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

```// 以 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
```

```// 簡化版的多型範例
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
```

```From Base
From Derived
From Base
```

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

```// 另一個多型範例
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 = []

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

```Woof
Meow
*Noise of a Hippo*
```

1. 自己想出一個練習