准备工作
- 有继承关系的两个类
- 两个类中有自己的属性、方法、构造方法、块、静态块、以及静态属性、静态方法等等
- 测试在main方法中创建子类对象后执行的顺序
父类Animal类
public class Animal {
//父类的普通属性
public String name="publicAnimalName";
//父类的静态属性
public static String context="staticAnimalContext";
//父类的普通块
{
System.out.println("Animal普通的构造块");
method();
}
//父类的静态块
static {
System.out.println("这是Animal类的静态属性:"+context);
System.out.println("Animal静态代码块");
staticMethod();
}
//父类的普通构造方法
public Animal(){
System.out.println("Animal无参数构造方法");
}
//父类的普通方法
public void method(){
System.out.println("这是普通的方法");
}
//父类的静态方法
public static void staticMethod(){
System.out.println("这是静态的方法");
}
}
子类Person类
//子类继承父类
public class Person extends Animal {
//子类的普通属性
public String name="publicPersonName";
//子类的静态属性
public static String context="staticPersonContext";
//子类的普通块
{
System.out.println("Person普通的构造块");
method();
}
//子类的静态块
static {
System.out.println("这是Person类的静态属性:"+context);
System.out.println("Person静态代码块");
staticMethod();
}
//子类的构造方法
public Person(){
//隐含代码-----------super();
System.out.println("Person无参数构造方法");
}
//子类的普通方法
public void method(){
System.out.println("这是普通的方法");
}
//子类的静态方法
public static void staticMethod(){
System.out.println("这是静态的方法");
}
}
测试类:
public class TestMain {
public static void main(String[] args) {
//加载类的过程---静态元素已经加载
Person p = new Person();
//通过调用子类的构造方法创建子类的对象,会有以下步骤:
//1.加载父类
//2.父类会产生自己的静态空间 属性 方法 块
//执行父类静态块
//3.加载子类
//4.子类会产生自己的静态空间 属性 方法 块
//执行子类静态块
//--------------------------------------------------
//5.开辟对象空间
//6.加载父类的非静态成员----属性 方法 块 构造方法
//7.执行父类块、执行父类构造方法
//8.加载子类的非静态成员----属性 方法 块 构造方法
//9.执行子类块、执行子类构造方法
//10.将对象空间的地址引用交给 变量来存储
}
}
测试结果: