Java polymorphism
First, the related class structure
Class A ... { //create by Danielinbiti public String Show (D obj) ... { return ("A and D"); } Public String Show (A obj) ... { return ("A and a"); } } Class B extends A ... {Public String show (B obj) ... { return ("B and B"); } Public String Show (A obj) ... { return ("B and A"); } } Class C extends B ... {} class D extends B ... {}
Second, the test run
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)); ⑨
Iii. Results of operation
① 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 A nd D
Iv. Summary
Take a a2=new B () as an example.
1, A2 can only access a information (refers to the compile-time compiler only know that A2 is a type, do not know the A2 specific sub-class object, only the runtime to know what to point to what object), and the subclass of the method of rewriting, also exists in the parent class, that is, the method of B override, a also has (if B has A2 also cannot be called directly), so A2 can access, but when called (note that this refers to the runtime), A2 is actually pointing to the B object, so the call is a B object with the same name as the same type parameter method. So A2.show (b) calls show (a obj) because A is not referenced to show (b obj).
Note: Compile time is compiler check syntax and type, runtime is parser parsing pseudo code for machine instruction, compile time compiler will check A2 access scope, that is, A2 access not more than a information will not error, the runtime parser will parse the code instruction of the method.
Java Multi-State explanation