public class Father {
private int i = test();
private static int j = method();
static {
System.out.println("father static code block");
}
Father() {
System.out.println("father constructor");
}
{
System.out.println("father common code block");
}
private static int method() {
System.out.println("father static method");
return 0;
}
public int test() {
System.out.println("father field method");
return 1;
}
}
/**
* 子类的实例化方法:
* 1. super()
* 1.1 父类的i = test()(被重写)
* 1.2 父类非静态代码块
* 1.3 父类的无参构造
* 2. i = test()
* 3. 子类的非静态代码块
* 4. 子类的无参构造
*
*/
public class Son extends Father{
private int i = test();
private static int j = method();
static {
System.out.println("son static code block");
}
Son() {
super();// 写或者不写都在,在子类构造器中一定会调用父类的构造器
System.out.println("son constructor");
}
{
System.out.println("son common code block");
}
private static int method() {
System.out.println("son static method");
return 0;
}
@Override
public int test() {
System.out.println("son field method");
return 1;
}
public static void main(String[] args) {
Son s1 = new Son();
System.out.println();
Son s2 = new Son();
}
}
输出结果:
father static method
father static code block
son static method
son static code block // 上面这部分是类初始化
son field method
father common code block
father constructor
son field method
son common code block
son constructor
son field method
father common code block
father constructor
son field method
son common code block
son constructor
解释
- 非静态实例变量显式赋值代码和非静态代码块代码按代码顺序从上往下执行
- 类变量显式赋值代码和静态代码块代码按代码顺序从上往下执行