【发布时间】:2012-08-31 18:44:05
【问题描述】:
实例变量什么时候初始化?是在构造函数块完成之后还是之前?
考虑这个例子:
public abstract class Parent {
public Parent(){
System.out.println("Parent Constructor");
init();
}
public void init(){
System.out.println("parent Init()");
}
}
public class Child extends Parent {
private Integer attribute1;
private Integer attribute2 = null;
public Child(){
super();
System.out.println("Child Constructor");
}
public void init(){
System.out.println("Child init()");
super.init();
attribute1 = new Integer(100);
attribute2 = new Integer(200);
}
public void print(){
System.out.println("attribute 1 : " +attribute1);
System.out.println("attribute 2 : " +attribute2);
}
}
public class Tester {
public static void main(String[] args) {
Parent c = new Child();
((Child)c).print();
}
}
输出:
父构造函数
子初始化()
父初始化()
子构造函数
属性 1:100
属性 2:空
-
属性 1 和 2 的内存何时分配到堆中?
-
想知道为什么属性 2 为 NULL ?
-
是否存在设计缺陷?
【问题讨论】:
-
顺便说一句,实例变量的 Java 术语是“字段”。
标签: java object inheritance abstract-class instance