在类的内部,变量定义的先后顺序决定了初始化的顺序。即使变量定义散布于方法定义之间,
它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。例如:
//: c04:OrderOfInitialization.java
// Demonstrates initialization order.
import com.bruceeckel.simpletest.*;
// When the constructor is called to create a
// Tag object, you'll see a message:
class Tag {
Tag(int marker) {
System.out.println("Tag(" + marker + ")");
}
}
class Card {
Tag t1 = new Tag(1); // Before constructor
Card() {
// Indicate we're in the constructor:
System.out.println("Card()");
t3 = new Tag(33); // Reinitialize t3
}
Tag t2 = new Tag(2); // After constructor
void f() {
System.out.println("f()");
}
Tag t3 = new Tag(3); // At end
}
public class OrderOfInitialization {
static Test monitor = new Test();
public static void main(String[] args) {
Card t = new Card();
t.f(); // Shows that construction is done
monitor.expect(new String[] {
"Tag(1)",
"Tag(2)",
"Tag(3)",
"Card()",
"Tag(33)",
"f()"
});
}
} ///:~
在 Card 类中,故意把几个 Tag 对象的定义散布到各处,以证明它们全都会在调用构造器或
其它方法之前得到初始化。此外,t3 在构造器内再次被初始化。
由输出可见,t3 这个引用会被初始化两次:一次在调用构造器前,一次在调用期间(第一次
引用的对象将被丢弃,并作为垃圾回收)。试想,如果定义了一个重载的构造器,它没有初
始化 t3;同时在 t3 的定义里也没有指定缺省值,那会产生什么后果呢?所以尽管这种方法
它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。例如:
//: c04:OrderOfInitialization.java
// Demonstrates initialization order.
import com.bruceeckel.simpletest.*;
// When the constructor is called to create a
// Tag object, you'll see a message:
class Tag {
Tag(int marker) {
System.out.println("Tag(" + marker + ")");
}
}
class Card {
Tag t1 = new Tag(1); // Before constructor
Card() {
// Indicate we're in the constructor:
System.out.println("Card()");
t3 = new Tag(33); // Reinitialize t3
}
Tag t2 = new Tag(2); // After constructor
void f() {
System.out.println("f()");
}
Tag t3 = new Tag(3); // At end
}
public class OrderOfInitialization {
static Test monitor = new Test();
public static void main(String[] args) {
Card t = new Card();
t.f(); // Shows that construction is done
monitor.expect(new String[] {
"Tag(1)",
"Tag(2)",
"Tag(3)",
"Card()",
"Tag(33)",
"f()"
});
}
} ///:~
在 Card 类中,故意把几个 Tag 对象的定义散布到各处,以证明它们全都会在调用构造器或
其它方法之前得到初始化。此外,t3 在构造器内再次被初始化。
由输出可见,t3 这个引用会被初始化两次:一次在调用构造器前,一次在调用期间(第一次
引用的对象将被丢弃,并作为垃圾回收)。试想,如果定义了一个重载的构造器,它没有初
始化 t3;同时在 t3 的定义里也没有指定缺省值,那会产生什么后果呢?所以尽管这种方法
似乎效率不高,但它的确能使初始化得到保证。