代码:
// 数字即表示执行顺序
class A {
String filed = func("5: filed of A");
static String staticFiled = func("1: static filed of A");
{
func("6: code block of A");
}
static {
func("2: static code block of A");
}
A() {
func("7: constructor of A");
}
static String func(String message) {
System.out.println(message);
return message;
}
}
class B extends A {
{
func("8: code block of B");
}
static {
func("3: static code block of B");// 接着是子类static file和static代码块
}
B() {
func("10: constructor of B");
}
String filed = func("9: filed of B");
static String staticFiled = func("4: static filed of B");
}
public class Test1 {
public static void main(String[] args) {
B b = new B();
}
}
输出:
1: static filed of A
2: static code block of A
3: static code block of B
4: static filed of B
5: filed of A
6: code block of A
7: constructor of A
8: code block of B
9: filed of B
10: constructor of B
总结
- static file和static代码块谁在前谁先执行
- filed和代码块谁在前谁先执行
- 构造函数最后执行
参考: