-->
public class ExtendsTest { 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(www.sxzhongrui.com(b)); //A and A
System.out.println(www.sxzhongrui.com(c)); //A and A
System.out.println(www.sxzhongrui.com(d)); //A and D System.out.println("=======");
System.out.println(a2.getClass().getName());
/**
* A a2 = new B();向上转型,a2调用show()方法之前先去判断父类A中是否有该方法
* 若有则调用B中相应的方法,若是带有参数的方法如www.sxzhongrui.com(b),其中b是B类型的,父类
* 中没有该方法,子类B中有该方法,但由于是向上转型不会直接调用B类中的方法,而是判断是否
* 父类中是否有参数b的父类型的同名方法(即A中没有show(B b)的方法而有show(A a)方
* 法),因此程序最终会调用B类中的show(A obj)方法。
* 因此a2.shw(b)、www.sxzhongrui.com(c)结果为B and A;www.sxzhongrui.com(d)结果为A and D
*/
System.out.println(www.sxzhongrui.com(b)); //B and A
System.out.println(www.sxzhongrui.com(c)); //B and A
System.out.println(www.sxzhongrui.com(d)); //A and D /**
* B b = new B();B类新建一个普通示例对象,www.sxzhongrui.com(b)的结果很明显就是B and B;
* www.sxzhongrui.com(c)父类和子类都没该方法(B中没有找到,转而到B的超类A里面找),因此转到第三优
* 先级,由于c是b的子类,因此到B类中找到show(B obj),最终结果B and B;
* www.sxzhongrui.com(d)在B类中没找到,转而倒父类中查找,调用父类的方法,结果A and D;
* 因为A、B中都有方法show(A obj),根据Java多态-方法的重写,最终调用子类中的方法,结
* 果B and A。
*/
System.out.println("=======");
System.out.println(www.sxzhongrui.com(b)); //B and B
System.out.println(www.sxzhongrui.com(c)); //B and B
System.out.println(www.sxzhongrui.com(d)); //A and D
System.out.println(www.sxzhongrui.com(a1)); //B and A /**
* 方法调用的优先问题 ,优先级由高到低依次为:www.sxzhongrui.com(O)、www.sxzhongrui.com(O)、www.sxzhongrui.com((super)O)、www.sxzhongrui.com((super)O)。
*/
}
} class A {
public A(){
System.out.println("A构造器被调用");
}
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}
}
class B extends A{
public B(){
System.out.println("B构造器被调用");
}
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{} -->