java多态性

public class PolyDemo09{
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

你可能会有疑惑,我们来看一下解释:

a1.show(b));Class A 中没有showB obj),B转向B的父类A,执行A showA obj--->return "A and A"

 

a1.show(c));Class A 中没有showC obj),C转向C的父类B,Class A 中没有showB obj),再转向父类A,执行A showA obj--->return "A and A"

 

a1.show(d));Class A 中有showD obj)执行A showD obj--->return "A and D"

 

这个比较特殊:A a2 = new B();父类声明,子类实例,你应该把a2当作子类重写完后的父类看,注意只有父类的方法。

 

a2.show(b));Class A 中没有showB obj),B转向B的父类A,执行A showA obj,Ashow 方法被重写,执行B showA obj--->return "B and A"

 

a2.show(c));Class A 中没有showC obj,C转向C的父类B,Class A 中没有showB obj,B转向父类A,执行A showA obj,Ashow 方法被重写,执行B showA obj--->return "B and A"

 

a2.show(d));Class A 中有showD obj)执行A showD obj--->return "A and D"

b.show(b)); Class B 中有showB obj--->return "B and B"

 

b.show(c)); Class B 中没有showC obj),C转向C的父类B,执行B showB obj--->return "B and B"

 

b.show(d)); Class B 中有继承了Class A showD obj,执行A showD obj--->return "A and D"




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值