Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

You need to describe a method as virtual if you want the ability to override its capabilities.

Code Block
borderStylesolid
titlePolymorphism with Rectangle and Square
borderStylesolid
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):
        super(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()

Note that, because Rectangle does not have a default, parameterless constructor, we must invoke Rectangle's constructor in the first line of Square's constructor (the super(width, width) part). Once again: when calling a superclass's constructor, it must be done on the first line.

No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
24.0
25.0
25.0

Even when casted to a Rectangle, s's .GetArea() functioned like if it were a Square.

An easier example to see is this:

Code Block
borderStylesolid
titleSimplified Polymorphism Example
borderStylesolid
class Base:
    virtual def Execute():
        return 'From Base'

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

b = Base()
d = Derived()

print b.Execute()
print d.Execute()
print cast(Base, d).Execute()
No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
From Base
From Derived
From Derived

If I were to leave out the virtual and {{override} keywords,

No Format
bgColor#D8DDE9
borderStylesolid
titleOutput w/o virtual
borderStylesolid
From Base
From Derived
From Base

...

Polymorphism is very handy when dealing with multiple types derived from the same base.

Code Block
borderStylesolid
titleAnother Polymorphism Example
borderStylesolid
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:
    animal.MakeNoise()
No Format
bgColor#D8DDE9
borderStylesolid
titleOutput w/o virtual
borderStylesolid
Woof
Meow
*Noise of a Hippo*

...