public class Polymorphism {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B(); //创建B对象,转化成A对象,拥有的成员方法是showD(),和覆盖掉show(A){A and A }的show(A){B and A}成员方法
B b = new B(); //B继承A,拥有showD()和show(A){B and A}成员方法
C c = new C();
D d = new D();
System.out.println(a1.show(b)); //使用a1的成员方法show(A)
System.out.println(a1.show(c)); //使用a1的成员方法show(A)
System.out.println(a1.show(d)); //使用a1的成员方法show(D)
System.out.println(a2.show(b)); //使用覆盖后的show(A)
System.out.println(a2.show(c)); //使用覆盖后的show(A)
System.out.println(a2.show(d)); //使用继承的show(D)
System.out.println(b.show(b)); //使用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
|
|