多态加载顺序

作为java三大特性之一,原来以为自己了解多态,直到看到了这道题发现自己还是做着做着就晕了,证明了还是不了解的呢

public class A {
    public String show(D obj) {
        return ("A and D");
    }

    public String show(A obj) {
        return ("A and A");
    } 

}

public class B extends A{
    public String show(B obj){
        return ("B and B");
    }
    
    public String show(A obj){
        return ("B and A");
    } 
}

public class C extends B{

}

public class D extends B{

}

public class Test {
    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("1--" + a1.show(b));
        System.out.println("2--" + a1.show(c));
        System.out.println("3--" + a1.show(d));
        System.out.println("4--" + a2.show(b));
        System.out.println("5--" + a2.show(c));
        System.out.println("6--" + a2.show(d));
        System.out.println("7--" + b.show(b));
        System.out.println("8--" + b.show(c));
        System.out.println("9--" + b.show(d));      
    }
}
开始分析执行顺序结果:

多态加载顺序优先级是this.show(o)->supper.show(o)->this.show(spper(o))->supper.show(sipper(o))

a1指的是A,this指的也是A,a1.show(b),去A中找show(B b)没有,父类是Object也没有,去A找show(b->a)找到,结果是"b and a"

针对第二条第三条有需要解释的是,如果有当前D,就直接找到了,没有就会d->b->a来找到了a

针对第四条的解释是:a2指的是A,this指向的是A,去A中找show(B b)没有,父类Object没有,去A找show(b->a)找到了,这个时候因为a2是指向子类实例的父类的引用,所以当B中也能找到show(A a)时,会重写,所以最终结果是"a and a"

其他结果类似,最终执行结果是:

1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D





猜你喜欢

转载自blog.csdn.net/zhangxiaomin1992/article/details/79023521
今日推荐