5. Polymorphism (polymorphism)
5.1 The concept of polymorphism
Three main characteristics of object-oriented: encapsulation, inheritance, polymorphism. From a certain point of view, encapsulation and inheritance are almost always prepared for polymorphism. This is our last concept and the most important point of knowledge.
Polymorphism definition: Allows different classes of objects to respond to the same message. That is, the same message can be used in a variety of different ways depending on the object being sent. (Sending a message is a function call)
The technology that implements polymorphism is called dynamic binding (dynamical binding), which is to determine the actual type of the referenced object during execution, and to invoke its corresponding method based on its actual type.
The role of polymorphism: to eliminate the coupling relationship between types.
In reality, there are numerous examples of polymorphism. For example, if you press the F1 key this action, if the current pop-up in the Flash interface is the help document as 3, if the current pop-up in Word is Word Help; Windows Help and support pops up under Windows. The same event occurs on different objects and produces different results.
Here are the three necessary conditions for polymorphic existence, requiring you to recite it when you dream!
5.2 The three necessary conditions of polymorphic existence
First, to have inheritance;
Second, to have to rewrite;
Third, the parent class reference points to the child class object.
Application of 5.3 testpolymoph.as--polymorphism to realize the benefits of polymorphism
Package {
public class Testpolymoph {
Public Function Testpolymoph () {
var cat:cat = new Cat ("MiMi");
var lily:lady = new Lady (cat);
var dog:dog = new Dog ("DouDou");
var lucy:lady = new lady (dog);
Lady.mypetenjoy ();
}
}
}
Class Animal {
private Var name:string;
function Animal (name:string) {
THIS.name = name;
}
Public function enjoy (): void {
Trace ("Call ...");
}
}
Class Cat extends Animal {
function Cat (name:string) {
Super (name);
}
Override public Function enjoy (): void {
Trace ("Miao Miao ...");
}
}
Class Dog extends Animal {
function Dog (name:string) {
Super (name);
}
Override public Function enjoy (): void {
Trace ("Wang Wang ...");
}
}
Suppose you add a new class bird
Class Bird extends Animal {
function Bird (name:string) {
Super (name);
}
Override public Function enjoy (): void {
Trace ("Jiji Zhazha");
}
}
Class Lady {
private Var Pet:animal;
function Lady (pet:animal) {
This.pet = pet;
}
Public Function Mypetenjoy (): void {
Just imagine if there's no polymorphism
If (pet is Cat) {Cat.enjoy ()}
If (pet is Dog) {Dog.enjoy ()}
If (pet is Bird) {Bird.enjoy ()}
Pet.enjoy ();
}
}