继承关系下代码的执行顺序

 1 //父类
 2 
 3 public class Father {
 4     static {
 5         System.out.println("这是父类的静态代码块");
 6     }
 7     {
 8         System.out.println("这是父类的构造代码块");
 9     }
10 
11     public Father(String m) {
12         System.out.println("这是父类的有参构造方法");
13     }
14 
15     public Father() {
16         System.out.println("这是父类的无参构造方法");
17     }
18 }
19 
20 //子类
21 public class Son extends Father {
22     static {
23         System.out.println("这是子类的静态代码块");
24     }
25     {
26         System.out.println("这是子类的构造代码块");
27     }
28 
29     public Son(String a) {
30         System.out.println("这是子类的有参构造方法");
31 
32     }
33 
34     public Son() {
35         System.out.println("这是子类的无参构造方法");
36 
37     }
38 }
39 //继承测试类
40 public class ExtendTest {
41 
42     public static void main(String[] args) {
43         System.out.println("测试类中主方法1");
44         Son son = new Son();
45         Son son2 = new Son("m");
46         System.out.println("测试类中主方法2");
47     }
48 
49 }
50 //执行结果
51 测试类中主方法1
52 这是父类的静态代码块
53 这是子类的静态代码块
54 这是父类的构造代码块
55 这是父类的无参构造方法
56 这是子类的构造代码块
57 这是子类的无参构造方法
58 这是父类的构造代码块
59 这是父类的无参构造方法
60 这是子类的构造代码块
61 这是子类的有参构造方法
62 测试类中主方法2
63 
64 //总结
65 //子类每次调用构造方法(不管有参无参)就会调用父类的无参构造方法。
66 //每次调用构造方法就会先执行该类的构造代码块
原文地址:https://www.cnblogs.com/19322li/p/10613397.html