静态数据的初始化

来源:互联网 发布:淄博网站搜索优化 编辑:程序博客网 时间:2024/05/21 17:39

static 关键字不能作用于局部变量,

public static void main(String[] args) {
// TODO Auto-generated method stub
static int num = 5;//这样是会报错的
}


public class Bowl {
public Bowl(int marker){
System.out.println("bowl--"+marker);
}

public void f1(int marker){
System.out.println("f1--"+marker);
}


}


public class Table {

static Bowl bowl1 = new Bowl(1);
Table(){
System.out.println("Table()");
bowl1.f1(1);
}

void f2(int marker){
System.out.println("f2--"+marker);
}

static Bowl bowl2 = new Bowl(2);


}


public 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 {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("create new cupboard() in main");
new Cupboard();
System.out.println();
System.out.println("create new cupboard() in main");
new Cupboard();
System.out.println();
table.f2(1);
System.out.println();
cupboard.f3(1);
System.out.println();




}


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
create new cupboard() in main
bowl--3
cupboard()--
f1--2


create new cupboard() in main
bowl--3
cupboard()--
f1--2


f2--1




总结:(摘自 编程思想)

初始化的顺序是先静态对象,而后是非静态对象。

总结一下对象的创建过程,假设有个名为Dog的类:

1.即使没有显示的使用static关键字,构造器实际上也是静态方法。因此,当首次创建类型为Dog的对象时(构造器可以看成静态方法),或者Dog类的静态方法/静态域首次被访问时,java解释器必须查找类路径,以定位Dog.class 文件。

2.然后载入Dog.class,有关静态初始化的所有动作都会执行,因此,静态初始化只在Class对象首次加载的时候进行一次。

3.当用new Dog()创建对象的时候,首先将在堆上为Dog对象分配足够的存储空间。

4.这块存储空间会被清零,这就自动的将Dog对象中的所有基本类型数据都设置成了默认值,而引用则被设置成了null。

5.执行所有出现于字段定义出的初始化动作。

6.执行构造器。

0 0
原创粉丝点击