类初始化与实例初始化
父类:
/**
* 父类初始化 <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 Code_03_Father {
private int i = test();
private static int j = method();
static {
System.out.print("(1)");
}
public Code_03_Father() {
System.out.print("(2)");
}
{
System.out.print("(3)");
}
public int test() {
System.out.print("(4)");
return 1;
}
public static int method() {
System.out.print("(5)");
return 1;
}
}
子类:
/**
* 子类的初始化 <clinit>
* 1、j = method()
* 2、子类的静态代码块
*
* 先初始化父类 (5)(1)
* 后初始化子类 (10) (6)
*
* 子类实例化方法:
* 1、super()(最前)
* 2、i = test() (9)
* 3、子类的非静态代码块 (8)
* 4、子类的无参构造(最后) (7)
*/
public class Code_03_Son extends Code_03_Father{
private int i = test();
private static int j = method();
static {
System.out.print("(6)");
}
public Code_03_Son() {
System.out.print("(7)");
}
{
System.out.print("(8)");
}
public int test() {
System.out.print("(9)");
return 1;
}
public static int method() {
System.out.print("(10)");
return 1;
}
public static void main(String[] args) {
Code_03_Son s1 = new Code_03_Son(); // 5 1 10 6 9 3 2 9 8 7
System.out.println();
Code_03_Son s2 = new Code_03_Son(); // 9 3 2 9 8 7
}
}
整体思路:
1、先对主函数 main
所在的类进行初始化 Son类 ,如果该类是继承了父类就需要先对父类初始化 Father 类;
2、类的初始化先初始化顺序由上而下,执行静态属性和静态方法;
3、然后就到了实例的初始化,由上而下,执行非静态属性和非静态方法,最后是构造方法;都是先父后子,注意:在执行非静态方法时,可能会涉及重写,new 出来的实例是什么就执行什么;比如:这里 new Son() 就执行Son类的重写方法;
1)那些方法不可以被重写
- final 声明的方法
- static 声明的方法
- private 等子类中不可见的方法
2)对象的多态性
- 子类如果重写了父类的方法,通过子类对象调用的一定是子类重写过的代码