多态之:深入多态

来源:互联网 发布:红楼梦服饰知乎 编辑:程序博客网 时间:2024/05/24 04:29

原文:感谢这位博主的分享,很清楚的讲了多态

长求总:

多态机制遵循的原则概括为:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法,但是它仍然要根据继承链中方法调用的优先级来确认方法,该优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)

施法材料:

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

    }

}

攻略:

我们分析5,a2.show(c),a2是A类型的引用变量,所以this就代表了A,a2.show(c),它在A类中找发现没有找到,于是到A的超类中找(super),由于A没有超类(Object除外),所以跳到第三级,也就是this.show((super)O),C的超类有B、A,所以(super)O为B、A,this同样是A,这里在A中找到了show(A obj),同时由于a2是B类的一个引用且B类重写了show(A obj),因此最终会调用子类B类的show(A obj)方法,结果也就是B and A。


0 0
原创粉丝点击