这是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); //在亲自写代码的过程中可以发现,f1是与Bowl里的f1关联
}
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 jingtaichushihua {
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) //初始化顺序是先静态对象,而后才是非静态对象,所以在执行main前回先初始化Static table...
* 因此,Table随后也会被加载.
Bowl(2)//这个结果我也理解了很久,原因是还是没有搞清静态对象的初始化顺序问题,
static Bowl bowl1 = new Bowl(1);执行完以后,执行的是static Bowl bowl2 = new 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)*/