初始化顺序??

chun799 2008-03-14 07:56:03
//: initialization/OrderOfInitialization.java
// Demonstrates initialization order.
import static net.mindview.util.Print.*;

// When the constructor is called to create a
// Window object, you'll see a message:
class Window {
Window(int marker) { print("Window(" + marker + ")"); }
}

class House {
Window w1 = new Window(1); // Before constructor
House() {
// Show that we're in the constructor:
print("House()");
w3 = new Window(33); // Reinitialize w3
}
Window w2 = new Window(2); // After constructor
void f() { print("f()"); }
Window w3 = new Window(3); // At end
}

public class OrderOfInitialization {
public static void main(String[] args) {
House h = new House();
h.f(); // Shows that construction is done
}
} /* Output:
Window(1)
Window(2)
Window(3)
House()
Window(33)
f()
*///:~

=======================================
//: polymorphism/Sandwich.java
// Order of constructor calls.
package polymorphism;
import static net.mindview.util.Print.*;

class Meal {
Meal() { print("Meal()"); }
}

class Bread {
Bread() { print("Bread()"); }
}

class Cheese {
Cheese() { print("Cheese()"); }
}

class Lettuce {
Lettuce() { print("Lettuce()"); }
}

class Lunch extends Meal {
Lunch() { print("Lunch()"); }
}

class PortableLunch extends Lunch {
PortableLunch() { print("PortableLunch()");}
}

public class Sandwich extends PortableLunch {
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
public Sandwich() { print("Sandwich()"); }
public static void main(String[] args) {
new Sandwich();
}
} /* Output:
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
*///:~

前一个是体现了变量在任何方法前得到初始化
.按此思想第二个应该输出是,
Bread()
Cheese()
Lettuce()
Meal()
Lunch()
PortableLunch()
Sandwich()

而正确答案不是,为什么?大家帮帮我,谢谢!!
注:此代码是 thinking in java 里面的
...全文
99 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
olivesoup 2008-03-14
  • 打赏
  • 举报
回复
看了你给我发的消息,不知道你对哪里还不明白,请你详细说明一下
olivesoup 2008-03-14
  • 打赏
  • 举报
回复
初始化顺序如下:
1。为对象分配内存
2。内存清零,使所有数据字段均填以默认值0,null等,也就是
private Bread b = null;
private Cheese c = null;
....
3。调用构造函数,显示或隐式调用父类构造函数,一直想上,直至最终调用object类中的构造函数,
因此new Sandwich();会一直想上追述到object类中的构造函数,然后逐级向下实例化,
因此顺序new Object()-->new Meal()-->new Lunch()-->new PortableLunch()-->new Sandwich()
4。上面在父类全部被实例化后,最后到实例化本类,调用本类构造函数
public Sandwich() { print("Sandwich()"); },在执行函数体内语句之前,会先将本类中任何带显示初始化
语句的数据字段附值,因此
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
被依次初始化。
5。最后执行public Sandwich() { print("Sandwich()"); }构造器内语句,初始化完成

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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