无继承的情况下执行顺序:
静态代码块->main方法->代码块->构造方法
有继承的情况下执行顺序:
父类静态代码块->子类静态代码块->main方法->父类代码块->父类构造方法->子类代码块->子类构造方法
package com.main.xxx;
/**
* 父类的初始化<clinit>:
* (1)j = method();
* (2)父类的静态代码块
*
* 父类的实例化方法:
* (1)super()(最前)
* (2)i = test();
* (3) 父类的非静态代码块
* (4) 父类的无参构造(最后)
*
* 非静态方法签名其实有一个默认的对象this
* this在构造器(或<init>)它表示的是正在创建的对象,因为这里是在创建Son对象,
* 所以test()执行的是子类重写的代码(面向对象多态)
*
* 这里i = test() 执行的是子类重写的test()方法
*/
public class Father {
private int i = test();
private static int j = method();
static {
System.out.println("(1)");
}
Father(){
System.out.println("(2)");
}
{
System.out.println("(3)");
}
public int test(){
System.out.println("(4)");
return 1;
}
public static int method(){
System.out.println("(5)");
return 1;
}
}
/**
* 子类的初始化<clinit>:
* (1)j = method();
* (2)子类的静态代码块
*
* 先初始化父类:(5)(1)
* 初始化子类:(10)(6)
*
* 子类的实例化方法:
* (1)super()(最前)
* (2)i = test();
* (3) 子类的非静态代码块
* (4) 子类的无参构造(最后)
*/
class Son extends Father{
private int i = test();
private static int j = method();
static {
System.out.println("(6)");
}
Son(){
// super();//写或不写都在,在子类构造器中一定会调用父类的构造器
System.out.println("(7)");
}
{
System.out.println("(8)");
}
public int test(){
System.out.println("(9)");
return 1;
}
public static int method(){
System.out.println("(10)");
return 1;
}
public static void main(String[] args) {
Son son = new Son();
System.out.println();
Son son1 = new Son();
}
}