Topic: 请教 (derived class 初始化问题)

  Print this page

1.请教 (derived class 初始化问题) Copy to clipboard
Posted by: floweret
Posted on: 2002-11-26 11:58

class Base {
  int i = 99;
  public void amethod(){ System.out.println("Base.amethod()"+i);}
Base() { amethod(); }
}
public class Derived extends Base{
  int i = -1;
  public static void main(String argv[]){
  Base b = new Derived();
//Derived无构造函数,所以默认构造函数调用super(),即先执行Base的构造函数,
//Base中调用函数amethod(),该amethod()调用的是Derived中的amethod()

System.out.println(b.i); //i为Base中i的值
  b.amethod(); //amethod()调用的是Derived中的amethod
}  
public void amethod(){ System.out.println("Derived.amethod()"+i); }
}
运行结果:Derived.amethod()0
99
Derived.amethod()-1

请问以上我注释部分理解的是否正确,运行结果第一行的i为何是0

2.answer [Re: floweret] Copy to clipboard
Posted by: SimonLei
Posted on: 2002-11-26 13:32

因为在Base的构造函数当中调用了amethod,
而这个实际上会调用Derived的amethod,此时
Derived本身并没有初始化,因此此时i =0;

3.thx,还有一点疑问 [Re: floweret] Copy to clipboard
Posted by: floweret
Posted on: 2002-11-27 08:44

谢谢,还有一点疑问,Derived本身既然还未初试化,那 i 此时定义了没有呢?

4.Re:thx,还有一点疑问 [Re: floweret] Copy to clipboard
Posted by: SimonLei
Posted on: 2002-11-27 08:49

floweret wrote:
谢谢,还有一点疑问,Derived本身既然还未初试化,那 i 此时定义了没有呢?


定义是你编译好了class就定义了的。
而没有初始化,是指没有执行那个赋值操作,
所以缺省值是0

5.Re:请教 [Re: floweret] Copy to clipboard
Posted by: floweret
Posted on: 2002-11-27 12:02

BlushBlushBlush

谢谢


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923