静态代码块,匿名代码块,无参构造器与有参构造器的执行顺序

看了Thinking In Java这本书,对于静态代码块,匿名代码块,无参构造器和有参构造器,上边对这部分讲的比较乱,整理一下:

class Cups{
	Cups(int i){
		System.out.println("This is a parameter constructor"+i);
	}
	
	Cups(){
		System.out.println("This is a non parameter constructor");
	}

	{
		System.out.println("This is an anonymous code block");
	}

	static{		
		System.out.println("This is a static code block");
	}
}
public class AnonymousConstructor {

	public static void main(String[] args) {
		new Cups();
		new Cups(1);
	}
}


执行结果为:

This is a static code block    //静态代码块最先执行,而且只执行一次

This is an anonymous code block  //匿名代码块在每次构造器初始化前都会执行

This is a non parameter constructor //有参和无参构造器的执行顺序与被调用的次序相同

This is an anonymous code block  //匿名代码块在每次构造器初始化前都会执行

This is a parameter constructor1


如果代码块换成类对象的初始化,执行结果也是一样的,例如:

class Cup{
	Cup(){
		System.out.println("This is a Cup constructor");
	}
}

class Cups{
	Cups(int i){
		System.out.println("This is a parameter constructor"+i);
	}
	
	Cups(){
		System.out.println("This is a non parameter constructor");
	}

	{
		System.out.println("This is an anonymous code block");
	}

	static{		
		System.out.println("This is a static code block");
		new Cup();
	}
}
public class AnonymousConstructor {

	public static void main(String[] args) {
		new Cups();
		new Cups(1);
	}
}
这段代码增加了一个辅助的类Cup,然后在静态代码块中调用,执行结果:
This is a static code block
This is a Cup constructor
This is an anonymous code block
This is a non parameter constructor
This is an anonymous code block
This is a parameter constructor1


你可能感兴趣的:(Java)