Inheritance
// this is pseudo code - isn
// base class references to derived-type objects.
BaseClass thing1 = new Derived1();
BaseClass thing2 = new Derived2();
BaseClass thing3 = new Derived3();
// assume the array elements must be of the same type
baseClassArray : [thing1, thing2, thing3];
for (int i-0; i< baseClassArray.Length; i++) {
baseClassArray[i].Foo(); // base.Foo() is called.
}
for (int i=0; i< baseClassArray.Length; i++) {
if (baseClassArray[i] is Derived1) {
Derived1 thingy1 = (Derived1)baseClassArray[i];
thingy1.Foo(); // derivedthe over-ride Foo() called
}else if ....
}
Polymorphism
// this is pseudo code - ish
public abstract class AbstractPainter {
public abstract void Style();
}
public class Dali : AbstractPainter {
public override Style() {
console.writeline("floppy clocks lying about");
}
public class Warhol : AbstractPainter {
public override Style() {
console.writeline("High contrast soup cans");
}
}
// cannot instantiate abstract classes
// ie. new AbstractPainter() is not allowed.
AbstractPainter Salvador = new Dali();
AbstractPainter Andy = new Warhol();
AbstractPainterArray = [Salvador, Andy];
for (int i=0; i< AbstractPainterArray.Length; i++) {
AbstractPainterArray[i].Style();
}
output:
"floppy clocks lying about"
"High contrast soup cans"
###Take Away?###
Inheritance: Same-type references + derived objects, same method call.
polymorphism: Same-type references + derived objects, different method call.