Polymorphism of Java
Polymorphism: the most important concept in object-oriented, which is embodied in Java in two ways:
Member variable call:
There are two types of reference variables in Java: compile time type and run-time type. The compile time type is determined by the type used to declare the variable, and the run-time type is determined by the object actually assigned to the variable. If compile time type is inconsistent with the runtime, polymorphism will occur.
Object polymorphism. In Java, a subclass object can replace the object reference of the parent class:
A subclass can be regarded as a special parent class, so the reference of the parent type can point to the object of the subclass: upward transformation.
If a reference type variable is declared as the type of the parent class, but actually refers to a subclass object, the variable can no longer access the properties and methods added in the subclass:
Student m = new Student();
m. School = "PKU '; / / legal, student class has school member variable
Person e = new Student();
e.school = "pku";// Illegal. Perosn class has no school member variable
The attribute is determined at compile time. At compile time, e is the person attribute and there is no school member variable. Therefore, there is a compilation error.
Virtual method call:
Normal method calls:
Virtual method call, in case of polymorphism:
At compile time, e is of person type, and the method call is determined at run time, so the getinfo () method of student class -- dynamic binding is called.
Summary:
Premise:
Member method:
Member variables: