Maybe after few days, we add a new class name Driver and extend the Person class, furthermore it also has its own way to have breakfast. So, we may like the same code.

var driver:Driver = new Driver();
driver.haveBreakfast();

Compare the three code segments, do you find something? Eh, we define different variables, not only the name but also the name. Then we call the same method.

What if we define the variables with the same name? Then the second statement will be the same. Maybe like

person.haveBreakfast().

Here, the “person” can be a Cook, an Author or driver. Eh, the work is not finish yet. Let’s turn to the variable definition.

How to deal with the type? Eh, they have different type.

Take a look at the class diagram.

The three subclasses are all inherited from the Person class. Remember the relationship between the superclass and the subclass? The subclass is an extension of the superclass, so the subclass can take the place of the superclass, because the superclass and the subclass have the methods in common. So, it’s ok in semantic.

Now, all we need is upcasting. That is use the superclass type variable refers to the subclass type instance.

Like the following code.

var person:Person = new Author();

Look at the class diagram; you should know the meaning of upcastingJ

The three code segment can be rewrite as

var person:Person = _______________
person.haveBreakfast().

You can fill the exactly data type to the blank. With different content in the blank, the program will do different action.

And this is call polymorphism. Polymorphism allows the programmer to treat derived class members just like their parent class’ members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior.

You know, one big principle of OOP is the OCP (open-closed principle). Open for the extension, closed for the modification. In our program, the main logic often stays stable, but we need to add new role to extends the program. Such as we add a new class Driver here, but the main logic doesn’t needs to be changed, we just need to modify the content in the blank. Less modification means less chance for bugs.

And this mechanism makes the code cleaner. If the language supports reflection, the code will be more beautiful.