overridden问题求解

CeleronWind 2003-07-30 11:16:37
问题如下:
23. What will happen when you attempt to compile and run the following code?
class Base{
int i = 99;
public void amethod(){
System.out.println("Base.amethod()");
}
Base(){
amethod();
}
}
public class Derived extends Base{
int i = -1;
public static void main(String argv[]){
Base b = new Derived();
System.out.println(b.i);
b.amethod();
}
public void amethod(){
System.out.println("Derived.amethod()");
}
}
A. Derived.amethod()
-1
Derived.amethod()
B. Derived.amethod()
99
Derived.amethod()
C. 99
D. 99
Derived.amethod()
E. compile time error.

我的答案是A
标答是B
解释如下:
23. B is correct. The reason is that this code creates an instance of the Derived class but assigns it to a reference of a the Base class. In this situation a reference to any of the fields such as i will refer to the value in the Base class, but a call to a method will refer to the method in the class type rather than its reference handle. But note that if the amethod() was not present in the base class then compilation error would be reported as at compile time, when compiler sees the statement like b.amethod(), it checks if the method is present in the base class or not. Only at the run time it decides to call the method from the derived class.

但还是没弄懂为什么b.i=99,哪位详细解释一下?
...全文
103 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
butian 2003-07-31
  • 打赏
  • 举报
回复
可以理解成
父类中的变量不能overriden
Javms 2003-07-31
  • 打赏
  • 举报
回复
我的理解是!当Base b = new Derived();时由于Derived继承至Base ,对象建立的规则是:
Derived类产生对象时会自动先产生其Base类的子对象包装与自己的对象内,因此对于构造函数是重Base类开始调用直到Derived类的构造函数,这是由编译器自动完成的!
CeleronWind 2003-07-31
  • 打赏
  • 举报
回复
up
CeleronWind 2003-07-31
  • 打赏
  • 举报
回复
up
mayanwei 2003-07-30
  • 打赏
  • 举报
回复
请注意: Base b = new Derived();

b的声明是Base, 题目答案解释的很明白:
此情况下 fields用父类 methods用子类

51,407

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧