参考:http://uule.iteye.com/blog/1558891
Java中的静态代码块是在虚拟机加载类的时候,就执行的,而且只执行一次。如果static代码块有多个,JVM将按照它们在类中出现的先后顺序依次执行它们,每个代码块只会被执行一次。
非静态代码块是在类new一个实例的时候执行,而且是每次new对象实例都会执行。
代码的执行顺序
- 主调类的静态代码块
- 对象父类的静态代码块
- 对象的静态代码块
- 对象父类的非静态代码块
- 对象父类的构造函数
- 对象的非静态代码块
- 对象的构造函数
示例代码
public class StaticBlockTest1 {
//主调类的非静态代码块
{
System.out.println("StaticBlockTest1 not static block"); } //主调类的静态代码块 static { System.out.println("StaticBlockTest1 static block"); } public StaticBlockTest1(){ System.out.println("constructor StaticBlockTest1"); } public static void main(String[] args) { Children children = new Children(); children.getValue(); } } class Parent{ private String name; private int age; //父类无参构造方法 public Parent(){ System.out.println("Parent constructor method"); { System.out.println("Parent constructor method--> not static block"); } } //父类的非静态代码块 { System.out.println("Parent not static block"); name = "zhangsan"; age = 50; } //父类静态代码块 static { System.out.println("Parent static block"); } //父类有参构造方法 public Parent(String name, int age) { System.out.println("Parent constructor method"); this.name = "lishi"; this.age = 51; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Children extends Parent{ //子类静态代码块 static { System.out.println("Children static block"); } //子类非静态代码块 { System.out.println("Children not static block"); } //子类无参构造方法 public Children(){ System.out.println("Children constructor method"); } public void getValue(){ //this.setName("lisi"); //this.setAge(51); System.out.println(this.getName() + this.getAge()); } }
输出结果
StaticBlockTest1 static block //主调类的静态代码块
Parent static block //父类的静态代码块 Children static block //子类的静态代码块 Parent not static block //父类的非静态代码块 Parent constructor method //父类的构造函数 Parent constructor method--> not static block Children not static block //主调类的非静态代码块 Children constructor method //主调类的构造函数 zhangsan50 //主调main方法
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
总结:
- 按照前面提到的顺序执行
- 子类定义无参构造方法,调用的父类也是无参构造方法