首页 > 代码库 > 对象初始化优先级

对象初始化优先级

初始化优先级:静态代码块>>main方法>>构造代码块>>构造函数

 

 1 package com.itinfo;
 2 
 3 /**
 4  * 代码块的优先级
 5  * http://www.cnblogs.com/goodcheap
 6  *
 7  * @author: Wáng Chéng Dá
 8  * @create: 2017-02-26 19:12
 9  */
10 public class CodeBlock {
11 
12     static {
13         System.out.println("go to------>>>>>(CodeBlock--static{})");
14         System.out.println("I am CodeBlock static code block!\n");
15     }
16 
17     {
18         System.out.println("go to------>>>>>(CodeBlock--{})");
19         System.out.println("I am CodeBlock code block!\n");
20     }
21 
22     public CodeBlock() {
23         System.out.println("go to------>>>>>(CodeBlock--CodeBlock(){})");
24         System.out.println("I am CodeBlock Constructor!\n");
25     }
26 
27 }
28 class TestCodeBlock extends CodeBlock {
29 
30     static {
31         System.out.println("go to------>>>>>(TestCodeBlock--static{})");
32         System.out.println("I am TestCodeBlock static code block!\n");
33     }
34 
35     {
36         System.out.println("go to------>>>>>(TestCodeBlock--{})");
37         System.out.println("I am TestCodeBlock code block!\n");
38     }
39 
40     public TestCodeBlock() {
41         System.out.println("go to------>>>>>(TestCodeBlock--public TestCodeBlock(){})");
42         System.out.println("I am TestCodeBlock Constructor!\n");
43     }
44 
45     public static void main(String[] args) {
46         System.out.println("go to------>>>>>(main)");
47         System.out.println("I am main method!\n");
48         CodeBlock block = new TestCodeBlock();
49     }
50 }

 

控制台输出:

go to------>>>>>(CodeBlock--static{})
I am CodeBlock static code block!

go to------>>>>>(TestCodeBlock--static{})
I am TestCodeBlock static code block!

go to------>>>>>(main)
I am main method!

go to------>>>>>(CodeBlock--{})
I am CodeBlock code block!

go to------>>>>>(CodeBlock--CodeBlock(){})
I am CodeBlock Constructor!

go to------>>>>>(TestCodeBlock--{})
I am TestCodeBlock code block!

go to------>>>>>(TestCodeBlock--public TestCodeBlock(){})
I am TestCodeBlock Constructor!

 

 

多态状态对象初始化优先级总结:父类静态代码块>>子类静态代码块>>main方法>>父类构造代码块>>父类构造函数>>子类构造代码块>>子类构造函数

 

对象初始化优先级