继承关系的类 加载机制 及执行过程.png
    例一:

    1. package test_load;
    2. public class Animal {
    3. public String test = "AnimalField";
    4. public static String testStatic = "AnimalStaticField";
    5. public Animal(){
    6. System.out.println("Animal中默认无参数的构造方法");
    7. }
    8. {
    9. this.test();
    10. System.out.println("Animal的普通程序块"+test);
    11. }
    12. static {
    13. Animal.testStatic();
    14. System.out.println("Animal的静态程序块"+testStatic);
    15. }
    16. public void test(){
    17. System.out.println("我是Animal中的普通方法");
    18. }
    19. public static void testStatic() {
    20. System.out.println("我是Animal中的静态方法");
    21. }
    22. }
    1. package test_load;
    2. public class Person extends Animal{
    3. public String test = "AnimalField";
    4. public static String testStatic = "AnimalStaticField";
    5. public Person(){
    6. //隐藏代码super();
    7. System.out.println("Person中无参数的构造方法");
    8. }
    9. {
    10. this.testPerson();
    11. System.out.println("Person的普通程序块"+test);
    12. }
    13. static {
    14. Person.testStatic();
    15. System.out.println("Person的静态程序块"+testStatic);
    16. }
    17. public void testPerson(){
    18. System.out.println("我是Person中的普通方法");
    19. }
    20. public static void testStatic() {
    21. System.out.println("我是Person中的静态方法");
    22. }
    23. }
    1. package test_load;
    2. public class RunMain {
    3. public static void main(String[] args){
    4. //加载类的过程 静态元素已经加载了
    5. //1.加载父类
    6. //2.父类产生自己的静态空间 加载静态空间时的顺序 加载属性 加载方法 加载块
    7. // 执行静态块
    8. //3.加载子类
    9. //4.子类产生自己的静态空间 加载属性 加载方法 加载块
    10. // 执行静态块
    11. //5.开辟对象空间
    12. //6.加载父类中的非静态成员 属性 方法 块 构造方法
    13. //7. 执行块 执行构造方法
    14. //8.加载子类中的非静态成员 属性 方法 块 构造方法
    15. //9. 执行块 执行构造方法
    16. //10.将对象空间的地址引用交给变量存储
    17. Person p = new Person();
    18. }
    19. }

    例二:

    1. public class Person {
    2. //public Person p = new Person();
    3. //这里如果添加这行代码 会出现错误 栈内存溢出错误StackOverflowError
    4. public static Person p1 = new Person();
    5. //静态初始化只执行一次
    6. //先输出普通程序块的内容
    7. //再输出构造方法
    8. //然后再执行静态块
    9. public String test = "AnimalField";
    10. public static String testStatic = "AnimalStaticField";
    11. public Person(){
    12. System.out.println("Person中无参数的构造方法");
    13. }
    14. {
    15. System.out.println("Person的普通程序块"+test);
    16. }
    17. static {
    18. System.out.println("Person的静态程序块"+testStatic);
    19. }
    20. public void testPerson(){
    21. System.out.println("我是Person中的普通方法");
    22. }
    23. public static void testStatic() {
    24. System.out.println("我是Person中的静态方法");
    25. }
    26. public static void main(String[] args){
    27. Person p1 = new Person();
    28. Person p2 = new Person();//静态初始化与静态块只会执行一次
    29. }
    30. }

    执行结果:
    Person的普通程序块AnimalField
    Person中无参数的构造方法
    Person的静态程序块AnimalStaticField
    Person的普通程序块AnimalField
    Person中无参数的构造方法
    Person的普通程序块AnimalField
    Person中无参数的构造方法