请结合http://blog.csdn.net/m1111121/article/details/8811757一起看
构造器初始化:
初始化顺序
局部变量中的基本数据类型是不会自动初始化话,但是全局变量就可以。
初始化顺序:静态数据(注意:static语句块 优先于 final static变量 优先于 static变量)于非静态数据(这个是按顺序来初始化的,有无final不影响)。变量初始化优先于构造器。
public class a {
static{
System.out.println("static语句块最先初始化");
}
final static int n=print("final static 其次初始化");
static int q=print("static最后初始化");
int m=print("一般非static的初始化");
final int mm=print("final 非static初始化");
static int print(String s){
System.out.println(s);
return 12;}
public static void main(String[] args){
a aa=new a();
}
}
static语句块最先初始化
final static 其次初始化
static最后初始化
一般非static的初始化
final 非static初始化
class Window{
Window(int n){
System.out.println("Window("+n+")");
}
}
class House{
Window w1=new Window(1);//before constructor
House(){
System.out.println("House()");
w3= new Window(33);//reinitialize w3
}
Window w2=new Window(2);//after constructor
void f(){System.out.println("f()");}
Window w3=new Window(3);//at end
}
public class Ini{
public static void main(String[] args){
House h=new House();
h.f();
}
}
结果:
静态数据的初始化
无论创建多少个对象,静态数据只占用一份储存区域。static关键字不能用于局部变量,只能作用于域。如果一个域是静态的基本类型域,且没有初始化,那么它就会获得基本类型的初值;如果它是一个对象的应用,那么它的初值就是null。静态数据只初始化一次
class Bowl{
Bowl(int n){
System.out.println("Bowl("+n+")");
}
void f1(int n){
System.out.println("f1("+n+")");
}
}
class Table{
static Bowl bowl1=new Bowl(1);
Table(){
System.out.println("Table");
bowl2.f1(1);
}
void f2(int n){
System.out.println("f2("+n+")");
}
static Bowl bowl2=new Bowl(2);
}
class Cupboard{
Bowl bowl