The same behavior, through different things, can manifest different forms. Polymorphism describes such a state.
Definition: refers to the same behavior, with multiple different manifestations.
Polymorphic premise
1. Inheritance or realization [choose one of two]
2. Method rewriting [meaning embodiment: no rewriting, meaningless]
3. The parent class reference points to the child class object [format embodiment]
Polymorphism
format
Parent type variable name = new subclass object;
Variable name. Method name ();
Fu z = new Zi (); // The parent class references the child class object
z.method (); // Call the method of subclass
Note: When using a polymorphic method to call a method, first check whether the method exists in the parent class, if not, then a compilation error; if it does, execute the method after the subclass has been rewritten
Benefits of polymorphism
The parent class type is used as the formal parameter of the method, and the subclass object is passed to the method, and the method is called, which can reflect the extensibility and convenience of polymorphism.
Reference type conversion
Upward transformation
Polymorphism itself is the process of upward conversion from subclass type to superclass type, which is the default.
Disadvantages:
Cannot use member variables and member methods specific to subclasses
Parent class variable name = new subclass type ();
Such as: Animal a = new Cat ();
Downward transformation: the premise must be polymorphic
The process of down-converting the parent type to the child type is mandatory.
Subclass type variable name = (subclass type) parent class variable name;
如:Cat c =(Cat) a;
Why transform
To call methods specific to subclasses, you must do a downward transformation.
Abnormal transformation
The cat object will be converted into a dog object will appear: ClassCastException
Avoid type conversion exceptions and make judgments before conversion
Variable name instanceof data type
If the variable belongs to the data type, return true.
If the variable does not belong to the data type, return false.
summary
For member variables, static methods look to the left; non-static methods: compile to the left and run to the right.
当父类变量引用子类对象时,在这个引用变量指向的对象中,他的成员变量和静态方法与父类是一致的;他的非静态方法,在编译时是与父类一致的,运行时却与子类一致(发生了重写)。