多态经典例子理解

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));      
    }
}

 

 

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

 

先说优先级,优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。this

这样来理解吧,当存在上相转型时,首先看子类有没有重写超类方法,若是调用类重写超类方法首先执行子类重写超类的方法,若是调用的子类没有重写超类的方法,直接调用超类的方法来执行,当不存在向上转型时,若是调用的方法在本类中存在则调用,反之 再好比⑧,b.show(c),b是一个引用变量,类型为B,则this为b,c是C的一个实例,因而它到类B找show(C obj)方法,没有找到,转而到B的超类A里面找,A里面也没有,所以也转到第三优先级this.show((super)O),this为b,O为C,(super)O即(super)C即B,所以它到B里面找show(B obj)方法,找到了,因为b引用的是类B的一个对象,所以直接锁定到类B的show(B obj),输出为"B and B”。code

相关文章
相关标签/搜索