5续)还是关于初始化~~看下面程序:
abstract class fruit{
abstract void grow();
public fruit(){
System.out.println("before grow()");
grow();
System.out.println("after grow()");
}
}
class apple extends fruit{
private int i = 1;
public apple(int i){
this.i = i;
System.out.println("count number = "+ i);
}
void grow(){
System.out.println("apple growing, count number = "+ i);
}
}
public class test{
public static void main(String[] args){
fruit a = new apple(5);
}
}
程序流程为:
从main()进入,生成一个apple()对象,new apple()将执行的动作:
1)为各个对象的成员变量进行分配空间,值均为二进制的零
2)在执行apple之类构造之前,先执行基类构造,在基类构造里又会调用子类的被重载的grow()方法。由于1)的缘故,此时i=0。
3)初始化子类的成员变量
4)调用子类构造
所以程序输出为:
before grow()
apple growing, count number = 0
after grow()
count number = 5