Java初始化顺序

1、在类的内部,变量的定义的先后顺序决定了初始化顺序,即使变量定义散布于方法定义间,他们仍旧会在不论什么方法(包含构造器)被调用之前得到初始化

2、静态数据的初始化

class Bowl{
Bowl(int marker){
print("Bowl("+marker+")");
}
void f1(int marker){
print("f1("+marker+")");
}

class Table{
static Bowl bowl1=new Bowl(1);
Table(){
print("Table()");
bowl2.f1(1);
}
void f2(int marker){
print("f2("+marker+")");
}
static Bowl bowl2=new Bowl(2);
}
}

class Cupboard{
Bowl bowl3=new Bowl(3);
static Bowl bowl4=new Bowl(4);

Cupboard(){
print("Cupboard()");
bowl4.f1(2);
}
void f3(int marker){
print("f3("+marker+")");
}
static Bowl bowl5=new Bowl(5);
}

public class StaticInitialization{
public static void main(String args[]){
print("Creating new Cupboard() in main");
new Cupboard();
print("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}

static Table table=new Table();
static Cupboard cupboard=new Cupboard();
}

output:

Bowl(1)

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)


3、显式的静态初始化

class Cup{
Cup(int marker){print("Cup("+marker+")");}
void f(int marker){print("f("+marker+")");}
}

class Cups{
static Cup cup1;
static Cup cup2;
static {
cup1=new Cup(1);
cup2=new Cup(2);
}

Cups(){
print("Cups()");
}

public class ExlicitStatic{
public static void main(String args[]){
print("Inside main()");
Cups.cup1.f(99);   //(1)
}

//static Cups cup1=new Cup();  //(2)
//static Cups cup2=new Cup();  //(2)
}
}

output:

Cup(1)

Cup(2)

f(99)


4、在public class和普通的class中的差异表现

在public class中,首先载入static变量和static块,然后载入main函数,不会载入非static块和非static变量

public class StaticBlockTest {
	static Block b1;
	Block b2 = new Block(2);
	static Block b3=new Block(3);
	{
		b2 = new Block(2);
		System.out.println("non static block");
	}
	
	public static void main(String args[]) {
		Block b = new Block(0);		
	}
	
	static{		
		b1 = new Block(1);
		System.out.println("static block");
	}
}

class Block {	
	public Block(int marker) {
		System.out.println("Block(" + marker + ")");
	}

}

output:

Block(3)
Block(1)
static block
Block(0)

在class中,仅仅有在实例化对象的时候才会载入静态块和非静态块

5、在继承中的初始化顺序

首先载入父类static块,然后是载入子类static块,然后载入父类,然后载入非static块,最后载入构造函数,在父类中相同遵循此顺序

public class InheritanceTest {
	public static void main(String []args){
		Dog d=new Dog();				
	}
}


class Animal{
    
    static int a=print(4);
    int c=print(5);
    Animal(){
        print(0);
    }
    
    public static int print(int i){
        System.out.println(i);
        return i;
    }
}

class Dog extends Animal{
    int b=print(2);
    Dog(){        
        System.out.println("b="+b);
    }
        
    static{
        //new Animal();  //(1)
        System.out.println("dog static");
    }
}


output:

4
dog static
5
0
2
b=2


通过创建父类的实例和在子类构造函数的super()都能够载入父类

假设去掉(1)处的凝视,output为:

4
5
0
dog static
5
0
2
b=2








posted @ 2014-12-26 19:45  mengfanrong  阅读(166)  评论(0编辑  收藏  举报