Three necessary conditions for polymorphic existence
First, to have inheritance;
Second, to have a rewrite;
The parent class reference points to the subclass object.
Code section:
classA { PublicString Show (D obj) {return("A and D"); } PublicString Show (A obj) {return("A and a"); }}classBextendsA { PublicString Show (B obj) {return("B and B"); } PublicString Show (A obj) {return("B and A"); }}classCextendsB {}classDextendsB {}
And then I started thinking:
Public Static voidMain (string[] args) {A A1=NewA (); A A2=NewB (); b b=NewB (); C C=NewC (); D d=NewD (); System.out.println (A1.show (A1)); System.out.println (A1.show (A2)); System.out.println (A2.show (A1)); System.out.println (A2.show (A2)); System.out.println (B.show (A1)); System.out.println (B.show (A2)); System.out.println (C.show (A1)); System.out.println (C.show (A2)); System.out.println (D.show (A1)); System.out.println (D.show (A2)); System.out.println ("Split Line **************************************"); 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)); System.out.println (C.show (b)); System.out.println (C.show (c)); System.out.println (C.show (d)); }
Operation Result:
A and AA and AB and AB, and AB and AB and AB, and AB and AB and A split line **************************************
a and AA and AA and DB and AB and AA and DB and BB and BA and DB and BB and BA and D
For ease of understanding, I have listed the method table for each class
b.show(A)
Java polymorphic Example