package pkg;
//1st class
class Bowel{
Bowel(int maker){//constructor
System.out.println("Bowel:"+maker);//【3】【5】【11】【13】【15】【22】【29】【36】
}
void f1(int maker) {//function 1
System.out.println("From Bowel f1:"+maker);//【8】【18】【25】
}
}
//2nd class
class Table{
static Bowel bowel1=new Bowel(1);/* 1st obj *///【2】
Table(){//constructor
System.out.println("Table:in constructor");//【6】
bowel2.f1(2);// one Bowel object //【7】
}
void f2(int maker) {//function 2
System.out.println("From Table f2:"+maker);
}
static Bowel bowel2=new Bowel(2);//later defined 【4】
}
//3rd class
class Cupboard{
Bowel bowel3=new Bowel(3);/* 3rd obj */ //【14】【21】【28】
static Bowel bowel4=new Bowel(4);//【10】
Cupboard(){
System.out.println("Cupboard:in constructor!");//【16】【23】【30】
bowel4.f1(4);//【17】【24】【31】
}
void f3(int maker) {
System.out.println("From Cupboard f3:"+maker);//【34】
System.out.println("From Cupboard f3:"+maker);//【34】
}
static Bowel bowel5=new Bowel(5);//【12】
}
//=====================================================================//
/* main class */
public class p95{
public static void main(String[] args){
System.out.println("Creating new Cupboard in main");//【19】
new Cupboard();//【20】
System.out.println("Creating new Cupboard in main again");//【26】
new Cupboard();//【27】
table.f2(1);//【32】
cupboard.f3(1);//【33】
Bowel t=new Bowel(1937);//【35】
}
//variable
static Table table=new Table();//【1】
//System.output.println("Between table and Cupboard");// NOT Allowed here
static Cupboard cupboard=new Cupboard();//【9】
Bowel b=new Bowel(9527);// will NOT be execute
}
OUTPUT:
----------------- go after statement [1] ----------------
【3】Bowel:1
【5】Bowel:2
【6】Table:in constructor
【8】From Bowel f1:2
----------------- go after statement [9] ----------------
【11】Bowel:4
【13】Bowel:5
【15】Bowel:3
【16】Cupboard:in constructor!
【18】From Bowel f1:4
---------------- go to main function -------------------
【19】Creating new Cupboard in main
【22】Bowel:3 //static variable initialized only ONCE
【23】Cupboard:in constructor!
【25】From Bowel f1:4
【26】Creating new Cupboard in main again
【29】Bowel:3
【30】Cupboard:in constructor!
【31】From Bowel f1:4
【32】From Table f2:1
【34】From Cupboard f3:1
【36】Bowel:1937
【测试】
如果将main中的所有创建对象的语句、以及【1】、【9】语句都删除,则除了【19】【26】外,没有其他任何语句输出。由此能得出第5条结论。
【总结】(另外参考p158):
1、对于一个类(包括主类),如果存在创建static变量,则先创建static变量。对于包括static变量初始化的主类,初始化之后才会执行main中语句。
2、对于一个类,创建static变量后,再创建非static变量,然后调用构造器。
3、static变量一旦创建后,不会再次创建。
4、主类中的main函数之外创建非static变量的语句不会被执行。
5、static变量初始化,仅仅在必要的时候才会进行。即,对于子类,仅仅在用其创建对象的时候,其static变量才会被初始化。