首先看一道题目如下:
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 继承 Father
public class Son extends Father{
private int i = test();
private static int j = method();
static {
System.out.println("6");
}
Son(){
System.out.println("7");
}
{
System.out.println("8");
}
@Override
public int test(){
System.out.println("9");
return 1;
}
public static int method(){
System.out.println("10");
return 1;
}
public static void main(String[] arg){
Son s1 =new Son();
System.out.println();
Son s2 = new Son();
}
}
1、考点
1)类初始化过程
2)实例初始化过程
3)方法的重写
2、类初始化过程
1)一个类要创建实例需要先加载并初始化该类
main 方法所在的类需要先加载和初始化
2)一个子类要初始化需要先初始化父类
3)一个类初始化就是执行 <clinit>() 方法。
<clinit>() 方法由静态变量显示赋值代码和静态代码组成。
类变量显示赋值代码和静态代码块代码从上到下顺序执行
<clinit>() 方法只执行一次
3、实例初始化过程
1)实例初始化就是执行 <init>() 方法
<init>() 方法可能重载有多个,有几个构造器就有几个 <init>() 方法
<init>() 方法由非静态实例变量显示赋值代码和非静态代码块,对应构造器代码组成
非静态实例变量显示赋值代码和非静态代码块从上到下顺序执行,而对应构造器的代码最后执行
每次创建实例对象,调用对应构造器,执行的就是对应的 ini方法
<init>() 方法的首行是super()和super(实参列表) ,即对应父类的 <init>() 方法
4、方法的重写
1)那些方法不可以被重写
final 声明的方法
static 声明的方法
private 等子类中不可见的方法
2)对象的多态性
子类如果重写了父类的方法,通过子类对象调用的一定是子类重写过的代码
非静态方法默认的调用对象是 this
this 对象在构造器或者说 <init>() 方法中就是正在创建的对象
结果如下:
(5)(1)(10)(6)(9)(3)(2)(9)(8)(7)
(9)(3)(2)(9)(8)(7)
代码如下:
/**
* 父类初始化 <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
}
}