Public classExtendstest { 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 (b)); //A and aSystem.out.println (A1.show (c));//A and aSystem.out.println (A1.show (d));//A and DSystem.out.println ("======="); System.out.println (A2.getclass (). GetName ()); /*** A a2 = new B (); Move up, A2 call the show () method to determine if there is a method in the parent Class A () if there is a corresponding method in B, if the method with parameters such as a2.show (b), where B is of type B, the parent class * Does not have this method in subclass B, but since it is not directly called by the method in class B, it is determined whether the parent class has a method with the same name as the parent type of parameter B (that is, a method without show (b) in a) and a show (a) party * method ), so the program will eventually invoke the show (A obj) method in Class B. * therefore A2.SHW (b), a2.show (c) result is B and a;a2.show (d) result is a and D*/System.out.println (a2.show (b)); //B and ASystem.out.println (A2.show (c));//B and ASystem.out.println (A2.show (d));//A and D /*** b b = new B (); Class B Creates a new normal sample object, and B.show (b) is obviously the result of B and b; * B.show (c) The parent and subclass do not have the method (b is not found, instead of the superclass a in B to find), so go to the third excellent * First class, because C is a subclass of B, so to Find Show (b obj) in class B, end result B and b; * B.show (d) not found in class B, instead of searching in the parent class, calling the method of the parent class, result A and D; * because there are methods in A and B show (a obj), according to JAV A polymorphic-method of rewriting, which ultimately calls the method in the subclass, Knot * fruit B and A. */System.out.println ("======="); System.out.println (B.show (b)); //B and BSystem.out.println (B.show (c));//B and BSystem.out.println (B.show (d));//A and DSystem.out.println (B.show (A1));//B and A /*** Method Invocation priority issues, priority from high to Low: This.show (O), Super.show (O), This.show ((Super) O), Super.show ((Super) O). */ }}classA { PublicA () {System.out.println ("A constructor is called"); } PublicString Show (D obj) {return("A and D"); } PublicString Show (A obj) {return("A and a"); } } classBextendsa{ PublicB () {System.out.println ("B constructor is called"); } PublicString Show (B obj) {return("B and B"); } PublicString Show (A obj) {return("B and A"); } } classCextendsb{}classDextendsb{}
Java Polymorphism (ii)