终极题!!!!!体会多态
5、运行下面程序,体会多态的特性.
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 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)); ⑨
问①――>⑨输出结果。
输出结果为:
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
提供给大家去细细体会一下。
当你完全了解输出的结果,那么多态也就理解透彻了。
[解决办法]
什么叫java 动态单分派 静态多分派 多态就显得很容易了
[解决办法]
不错 支持楼主
[解决办法]
System.out.println(a1.show(b)); //A and A //没有找到对B类实例的方法,但有其父类A实例的方法,故作为A类实例传入 System.out.println(a1.show(c)); //A and A //同上 System.out.println(a1.show(d)); //A and D //A类有对D类实例的方法,作为D类实例传入 System.out.println(a2.show(b)); //B and A //(父类引用子类对象,只有父类的方法,但B类重写了A类方法) //父类A没有对B类实例的方法,作为A类实例传入 System.out.println(a2.show(c)); //B and A //同上 System.out.println(a2.show(d)); //A and D //下面是B类继承A类,有A,B类方法,B类重写父类对A实例的方法 System.out.println(b.show(a1));//B and A 这个我自己加,为说明方法给重写了 System.out.println(b.show(b)); //B and B System.out.println(b.show(c)); //B and B System.out.println(b.show(d)); //A and D }}
[解决办法]
第四个 第五个才是精髓
[解决办法]
哈哈哈
很勃起这个题
[解决办法]
看到 的太晚了
[解决办法]