楔子
菜鸟的学习笔记。
类的初始化
以Dog的类概括一下创建对象的过程
- 即使没有显示地使用static关键字,构造器实际上也是静态方法。所有,当首次创建Dog 类型的对象或是首次访问Dog类的静态方法或属性时,Java解释器必须在类路径中查找,以定位Gog.class
- 当加载完Dog.class后,有关静态初始化的所有动作都会执行。因此,静态初始化只会在首次加载Class对象时初始化一次。
- 当用new Dog()创建对象时,首先会在堆上为Dog对象分配足够的存储空间。
- 分配的存储空间首先会被清零,即会将Dog对象中的所有基本类型数据设置为默认值(数字会被置0,布尔型和字符型也相同)。引用被置为null。
- 执行所有出现在字段定义出的初始化动作。
- 执行构造器。
类初始化
class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f1(int marker) {
System.out.println("f1(" + marker + ")");
}
}
class Table {
static Bowl bowl1 = new Bowl(1);
// Bowl bowl1 = new Bowl(1);//静态 变量先初始化,然后才是 非静态变量
Table() {
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
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 marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println("main creating new Cupboard()");
new Cupboard();
System.out.println("main creating new Cupboard()");
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)
main creating new Cupboard()
Bowl(3)
Cupboard()
f1(2)
main creating new Cupboard()
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
进程已结束,退出代码 0