The three main characteristics of object-oriented: encapsulation, inheritance and polymorphism. Polymorphism is an important mechanism for code reuse in programming, which indicates that there are different semantics when the same operation works on different objects.
Java polymorphism mainly has the following two ways of expression:
1) method overloading (overload). Overloading refers to multiple methods with the same name in the same class, but these methods must be differentiated on the parameter list, either with different number of arguments or different types of parameters in the same location.
2) method override (override). Subclasses can override methods of the parent class. A reference to a parent class can point not only to its instance object, but also to the instance object of the child class. The reference variable of an interface can also point to an instance object of its implementation class.
The calling method of a program is dynamically bound at run time, that is, the method that references the specific instance object to which the variable is pointing, rather than the method defined in the type of the reference variable. This dynamic binding enables polymorphism. Only the runtime is able to determine which method is called specifically. So an instance covered by a method is also known as run-time polymorphism .
Note that member variables are not polymorphic , and the value of the member variable depends on the type of the defined variable .
public class Father { int i=1; public void A () {System.out.println ( "Father a" ); public void b () {System.out.println ( "Father B" ); }}
public class Son extends father{ public int i=5; public void A () {System.out.println ( "Son a" ); public void b () {System.out.println ( "Son B" ); public void C () {System.out.println ( "Son C" ); }}
Public Static void Main (string[] args) { Father Father=new Son (); FATHER.A (); Father.b (); // father.c (); Error System.out.println (father.i); Son son=(son) father; The principle of the parent class being cast to a subclass: the reference of the parent type to the instance of which subclass, which can be converted to the reference son.c () of which subclass; System.out.println (SON.I);
throws an exception Java.lang.ClassCastException:Father cannot is cast to Son
Son son= (son) new Father ();
}
Output:
son aSon b1son c5
Implementation mechanism of JAVA SE polymorphism