口诀
一、执行初始化方法
如果该类有父类,先执行父类的初始化方法,后执行子类初始化方法。
初始化方法主要涉及两个:
①静态显式赋值变量
②静态代码块
注: (1)①和②依据在代码中的顺序来执行,自上而下
二、执行实例化方法
实例化方法主要为四步:
①super()(最前)
②非静态显式赋值变量
③非静态代码块
④无参构造方法(最后)
注: (1)②和③依据在代码中的顺序来执行。 (2)非静态方法调用时前面有一个this,this表示正在创建的对象,例如实例化子类的过程中,调用了父类的非静态方法,并且该方法被子类重写了,那么调用的其实是子类的实现。
三、示例代码
Father.class
/*** 父类初始化<clinit>* 1、j = method()* 2、 父类的静态代码块** 父类实例化方法:* 1、super()(最前)* 2、i = test() (9)* 3、子类的非静态代码块 (3)* 4、子类的无参构造(最后)(2)*** 非静态方法前面其实有一个默认的对象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;}}
Son.class
/*** 子类的初始化<clinit>* 1、j = method()* 2、子类的静态代码块** 先初始化父类 (5)(1)* 初始化子类 (10) (6)** 子类实例化方法:* 1、super()(最前* 2、i = test() (9)* 3、子类的非静态代码块 (8)* 4、子类的无参构造(最后)(7)*/public 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();}}
