One, polymorphic overview
Polymorphism is the third most characteristic of object-oriented after encapsulation and inheritance.
Real things often reflect a variety of forms, such as students, students are a kind of people, then a specific classmate Zhang San is a student is also a person, that appears two forms.
Java, as an object-oriented language, can also describe the various forms of a thing. If the student class inherits the person class, a student object is both student and person.
Format: Refers to the parent class reference to the Child class object
Parent class type variable name =new subclass type ();
Ii. Characteristics of polymorphic members
A: polymorphic member variables
When a member variable of the same name appears in the child parent class, when the variable is called by polymorphic:
Compile time: Refer to whether the referenced variable belongs to a class that has a called member variable. No, compilation failed.
Run time: is also a member variable in the class to which the reference variable belongs.
Simple: Compile and run all refer to the left side of the equals sign. Compile run look to the left.
B: Polymorphic Member method
Compile time: The reference variable belongs to the class, and if there are no methods called in the class, the compilation fails.
Run Time: Refer to the class to which the object refers to the reference variable, and run the member method in the class to which the object belongs.
In short: Compile to see the left, run to the right
Third, transition up and down in polymorphic
The transformation of polymorphism is divided into two types: upward transformation and downward transformation.
A: Upward transformation: When there are sub-class objects assigned to a parent class reference, is the upward transformation, polymorphism itself is the process of upward transformation.
Use format: When the student class inherits the person class
Person P=new Student ();
B: A downward transition: a subclass object that has been transformed upward can use a format that enforces type conversions and converts a parent class reference to a subclass reference, which is a downward transformation. If the parent class object is created directly, it cannot be transformed downward.
Use format: Student stu= (Student) p;
Iv. Advantages and Disadvantages
Advantages and disadvantages of polymorphism
Advantages: Improved maintainability (guaranteed by polymorphic prerequisites) and improved Code extensibility
Disadvantage: You cannot directly access members that are specific to subclasses
java--polymorphism