Understanding of Polymorphism in Java
What is polymorphic?
1. Object-oriented three major features encapsulation, inheritance, polymorphism, from a certain point of view, encapsulation and inheritance are prepared for polymorphism.
2. Polymorphic definition: Allows different classes to react to the same message, which means that the same message can be used in a variety of different ways depending on the sending object.
3. The technique of implementing polymorphism, called dynamic binding, is the actual type of the referenced object that is judged during execution, and its corresponding method is called according to its actual type.
4. The role of polymorphism is to eliminate the coupling between types.
Examples of real-life polymorphism: For example, F1 is Word's help document in Word, and Eclipse is the help document for Eclipse, which plays a different role in different classes.
Three prerequisites for polymorphic presence:
1. Inheritance,
2. Rewrite,
3. The parent class reference points to the subclass object.
A classic case.
Package homework;
public class A {
Public String Show (D obj) {
Return ("A and D");
}
Public String Show (A obj) {
Return ("A and a");
}
}
//
Package homework;
public class B extends a{
Public String Show (B obj) {
Return ("B and B");
}
Public String Show (A obj) {
Return ("B and A");
}
}
//
Package homework;
public class C extends b{
}
//
Package homework;
public class D extends b{
}
//
Package homework;
Import Org.omg.Messaging.SyncScopeHelper;
Public class Lei {
Public static void Main (string[] args) {
a a1 = new A ();
A a2 = new B ();
b b = new B ();
c C = new C ();
D d = new D ();
System.out.println (a1.show (b)); ①
System.out.println (A1.show (c)); ②
System.out.println (A1.show (d)); ③
System.out.println (a2.show (b)); ④
System.out.println (A2.show (c)); ⑤
System.out.println (A2.show (d)); ⑥
System.out.println (b.show (b)); ⑦
System.out.println (B.show (c)); ⑧
System.out.println (B.show (d)); ⑨
}
}
Answer:
A and a
A and a
A and D
B and A
B and A
A and D
B and B
B and B
A and D
Explanation: For ①A1 called the Show (a obj) method in a, ② is the same as ①, and three calls the show (D obj) method in a
In the case of ④,⑤,⑥, ④,⑤ is an upward transformation, assigning an instance of a subclass to a parent class reference, overriding the same method in the parent class during an upward transformation, that is, rewriting, and for ⑥ does not rewrite the show (D obj) method in a
For ⑦,⑧,⑨, it is good to understand that B.show (b) invokes the method in B, almost as much as the ①,②,③ reader can understand.
The understanding of polymorphism in Java