For polymorphism, let's look at a simple example
classa{ Public voidA1 () {System.out.println ("1"); } Public voidA2 () {System.out.println ("2"); } } Public classTest2extendsa{ PublicTest2 () {//TODO auto-generated Constructor stub } Public voidA1 () {System.out.println ("3"); } Public voidA2 () {System.out.println ("4"); } Public Static voidMain (string[] args) {Test2 T1=NewTest2 (); A T2=NewTest2 (); T1. A1 (); T1. A2 (); T2. A1 (); T2. A2 (); }}
As can be seen from the above example, the subclass overrides the base class's A1 (), A2 () method, and then establishes two subclass objects, one of which is assigned to the sub-type reference T1, and the other a reference T2 to the base type. Next, call the A1, A2 method on the two references respectively.
3
4
3
4
Above is the output, T1 because it is the test2 type, so the result of the subclass A1,a2 method is displayed correctly. But then the T2 is the base type, and it looks like the result of the base class A1,a2 method should be output, but the compiler is outputting the result of the subclass A1,a2 method. In fact, this is the manifestation of polymorphism, here to refer to late binding this
Concept, late binding is done by the compiler, and at compile time, the compiler does not need to obtain any special information to make the correct call.
In simple terms, a reference to a parent type can point to an object of a subtype.
There is also a way to invoke a parent class with a reference to a parent class that does not have a method of forcing the type conversion, for example
A T1 = new Test1 ();
Test1 t3 = (Test1) t1;
T3. A3 (); The A3 hypothesis here is a subclass-specific method.
In the words of Java programming, polymorphism is an important technology that allows programmers to "separate things from the unchanging", and the code modifications we make do not destroy other parts of the program that should not be affected.
Note: Static methods can only inherit and not override, that is, if the subclass inherits the static method of the base class, if it is called, it depends on what type of reference is the base type or subtype, and whose method is called.
Finally, we summarize the characteristics of polymorphism:
The first thing to do is to have an inheritance, and then the base class method is overridden, and the method must be public, and the object created by the last subclass will point to the reference to the parent class.
Learn about the nature of Java inheritance, polymorphism, abstract classes, interfaces, and more (2)