Java的继承和多态

看了博客园里面的一个文章,关于java的继承和多态:
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 答案 4 5 6
关键点就在与对A a2 = new B();的理解。
栈中的引用变量是A,堆中的实例变量是B。
将子类的实例,赋值给父类的引用。就是向上转型。
向上转型,在运行时,会遗忘子类对象中与父类对象中不同的方法。也会覆盖与父类中相同的方法--重写。(方法名,参数都相同)
所以a2,可以调用的方法就是,A中有的,但是B中没有的方法,和B中的重写A的方法。
上一篇:iOS UI基础-4.2应用程序管理 Xib文件使用


下一篇:Integer Intervals(贪心)