# 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 = []
list.Add(Dog())
list.Add(Cat())
list.Add(Hippo())

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

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

1. 自己想出一个练习