当前位置: 技术问答>java相关
初学JAVA,问题02!
来源: 互联网 发布时间:2015-10-30
本文导语: 摘自THINK IN JAVA,各位能给出你们的答案吗? 我是想问static的对象初始化在普通对象前还是后呀,比构造函数早吗? static对象和非静态对象的区别? class Bowl { Bowl(int marker) { System.out.println("Bowl(" + marker...
摘自THINK IN JAVA,各位能给出你们的答案吗?
我是想问static的对象初始化在普通对象前还是后呀,比构造函数早吗?
static对象和非静态对象的区别?
class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Table {
static Bowl b1 = new Bowl(1);
Table() {
System.out.println("Table()");
b2.f(1);
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);
}
class Cupboard {
Bowl b3 = new Bowl(3);
static Bowl b4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
b4.f(2);
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println(
"Creating new Cupboard() in main");
new Cupboard();
System.out.println(
"Creating new Cupboard() in main");
new Cupboard();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupboard t3 = new Cupboard();
}
我是想问static的对象初始化在普通对象前还是后呀,比构造函数早吗?
static对象和非静态对象的区别?
class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Table {
static Bowl b1 = new Bowl(1);
Table() {
System.out.println("Table()");
b2.f(1);
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);
}
class Cupboard {
Bowl b3 = new Bowl(3);
static Bowl b4 = new Bowl(4);
Cupboard() {
System.out.println("Cupboard()");
b4.f(2);
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println(
"Creating new Cupboard() in main");
new Cupboard();
System.out.println(
"Creating new Cupboard() in main");
new Cupboard();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupboard t3 = new Cupboard();
}
|
呵呵,你看是很认真的啊!要彻底了解JAVA的编译机制是要花一番工夫的!
这里的初始化我也看过了,首先初始化所有static对象,如果有继承,就先构造父类,然后子类,最后是构造MAIN中的对象
这里的初始化我也看过了,首先初始化所有static对象,如果有继承,就先构造父类,然后子类,最后是构造MAIN中的对象
|
当然要早,在Class对象首次载入的时候,static对象首先被初始化,而且只初始化一次
|
是啊
先初始化
我也在学习THINKING IN JAVA
希望多多交流哦
先初始化
我也在学习THINKING IN JAVA
希望多多交流哦