总结下对象的创建过程,假如有个名称为Dog的类:
- Java解析器查找类路径,以定位Dog.class文件。即使没有显式地使用static关键字,构造器实际上也是静态方法。因此,当首次创建Dog对象时,或者Dog类的静态方法/静态域首次被访问,都会激发创建对象的过程。
- 然后载入Dog.class。有关静态初始化的所有动作都会执行。因此,静态初始化只有在Class对象首次加载的时候进行一次。
- 当用new Dog()创建对象的时候,首先将在堆上为Dog对象分配足够的存储空间。
- 执行所有出现于字段定义处的初始化动作。基本类型收设置为默认值,而引用则被设置成了null。
- 执行构造器
下面分享一段Thinking in Java的代码片段,已说明
class Bowl{
Bowl(int market){
System.out.println("Bowl(" + market + ")");
}
void f1(int market){
System.out.println("f1(" + market + ")");
}
}
class Table{
static Bowl bowl1 = new Bowl(1);
Table(){
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int market){
System.out.println("f2(" + market + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard{
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard(){
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int market){
System.out.println("f3(" + market + ")");
}
static Bowl bowl5 = 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();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
输出结果是:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
网友评论