Java静态变量和构造函数的执行顺序
案例:
package com.devin;
public class MyMain {
public static void main(String args[]) {
Father f = new Son();
}
}
class Father {
public Father() {
System.out.println("Father Construct");
}
static int a=printFahter();
static int printFahter() {
System.out.println("print in father");
return 1;
}
}
class Son extends Father {
public Son() {
System.out.println("Son Construct");
}
static int b=printSon();
static int printSon() {
System.out.println("print in son");
return 2;
}
}
输出结果:
print in father
print in son
Father Construct
Son Construct
结论,静态变量和构造函数的执行顺序:
1、父类的静态变量;
2、子类的静态变量;
3、父类的构造函数;
4、子类的构造函数;
--------------------------------------------------------------------
PS: 欢迎关注公众号"Devin说",会不定期更新Java相关技术知识。
--------------------------------------------------------------------