我們給出一段父類引用指向子類對象的經典代碼,以讓您分析其運行結果和更加深入了解這個原理的精妙之處:
package cn.bjsxt.oop03;
public class Test1 {
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(a1.show(b));
System.out.println(a1.show(c));
System.out.println(a1.show(d));
System.out.println(a2.show(b));
System.out.println(a2.show(c));
System.out.println(a2.show(d));
System.out.println(b.show(b));
System.out.println(b.show(c));
System.out.println(b.show(d));
}
}
class A{
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}
}
class B extends A{
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{
}
//這是運行結果
A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
2017/10/24 BIT创作,您可以免费转载和使用!(本模块博客是作者学习期间整理的学习心得,不是java技术的标准严格学习文档,仅作参考交流使用,对于使用本文档的后果,作者不作任何口头或书面的承诺)