Polymorphism
Although Example 4.17 instantiates an instance of class Blimp, you assign the object to a variable of type Aircraft. Dart supports polymorphism. Polymorphism allows a family of objects to adhere to a single interface while allowing different implementations. Let’s add another concrete class named Plane (Figure 4.1).
EXAMPLE 4.18
class Plane extends Aircraft
{
Plane()
{
this.maxspeed = 537;
this.name = "Plane";
}
void showSmoke()
{
print('--Show Smoke--');
}
}
main() {
Aircraft craft;
craft = new Blimp(73);
craft.turnOn();
craft.goForward();
craft.turnOff();
craft = new Plane();
craft.turnOn();
craft.goForward();
craft.turnOff();
}
//Output:
//--Turns On--
//--Blimp moves forward--
//--Turns Off--
//--Turns On--
//--Plane moves forward--
//--Turns Off--
FIGURE 4.1 Inheritance chain and class interfaces
Example 4.18 defines a new concrete implementation named Plane, which, just like Blimp, also extends the class Aircraft. The main() function declares a local variable of type Aircraft.
Using polymorphism, you can instantiate Blimp and Plane and assign them to the variable of type Aircraft. Since both are descendants of Aircraft, you can act upon their shared properties. Each object instance retains its own distinctive class properties and instance values, and their output is unique to each object’s respective class instance.
Plane implements a custom method of showSmoke(), which is not part of the parent class Aircraft. This means that although you have an instance of Plane, the variable of type Aircraft does not know about Plane’s implementation. If you want to access showSmoke() through a variable, you will have to assign the Plane instance to a variable of type Plane.
main() {
...
//craft.showSmoke(); //The method 'showSmoke' is not defined for the class
Plane aPlane = new Plane();
aPlane.showSmoke(); //prints --Show Smoke --
}