您的位置:首页 > 编程语言 > Java开发

Java 静态语句块、语句块、构造函数执行顺序

2018-01-12 14:53 253 查看
简单代码:

package example;

class Parent {
static String name = "hello";

{
System.out.println("3 parent block");
}

static {
System.out.println("1 parent static block");
}

public Parent() {
System.out.println("4 parent constructor");
}
}

class Child extends Parent {
static String childName = "hello";

{
System.out.println("5 child block");
}

static {
System.out.println("2 child static block");
}

public Child() {
System.out.println("6 child constructor");
}
}
package example;

public class StaticIniBlockOrderTest {
public static void main(String[] args) {
new Child();
}
}

输出结果:
1 parent static block

2 child static block

3 parent  block

4 parent constructor

5 child  block

6 child constructor

执行顺序总结:

1、执行父类静态代码块,执行子类静态代码块

2、执行父类非静态代码块,执行父类构造函数,执行子类非静态代码块,执行子类构造函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: