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

static代码块、成员变量初始化、构造方法执行顺序

2016-07-01 21:00 441 查看
下面代码:

public class Son{
Father father = new Father();
static{
System.out.println("Son static");
}
public Son(){
System.out.println("Son()");
}
}

public class Father {
static{
System.out.println("Father static");
}
public Father(){
System.out.println("Father()");
}
}

public class Main{
public static void main(String[] args){
Son son = new Son();
}
}


结果:

Son static
Father static
Father()
Son()


结论

先执行static代码块,再初始化成员变量,再执行构造方法。

下面代码:

public class Son extends Father{
//Father father = new Father();
static{
System.out.println("Son static");
}
public Son(){
System.out.println("Son()");
}
}

public class Father {
static{
System.out.println("Father static");
}
public Father(){
System.out.println("Father()");
}
}

public class Main{
public static void main(String[] args){
Son son = new Son();
}
}


结果:

Father static
Son static
Father()
Son()


结论

先执行父类的static代码块,再执行子类static,再执行构造方法。

下面代码:

public class Son extends Father{
Father father = new Father(1);
static{
System.out.println("Son static");
}
public Son(){
System.out.println("Son()");
}
}

public class Father {
static{
System.out.println("Father static");
}
public Father(){
System.out.println("Father()");
}
public Father(int a){
System.out.println("Father(1)");
}
}

public class Main{
public static void main(String[] args){
Son son = new Son();
}
}


结果:

Father static
Son static
Father()
Father(1)
Son()


结论

先执行父类的static代码块,再执行子类static,再执行父类构造方法,再再初始化成员变量,再走子类构造方法剩下的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: