对象初始化优先级
Posted Chinda
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象初始化优先级相关的知识,希望对你有一定的参考价值。
初始化优先级:静态代码块>>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{}) go to------>>>>>(TestCodeBlock--static{}) go to------>>>>>(main) go to------>>>>>(CodeBlock--{}) go to------>>>>>(CodeBlock--CodeBlock(){}) go to------>>>>>(TestCodeBlock--{}) go to------>>>>>(TestCodeBlock--public TestCodeBlock(){}) |
多态状态对象初始化优先级总结:父类静态代码块>>子类静态代码块>>main方法>>父类构造代码块>>父类构造函数>>子类构造代码块>>子类构造函数
以上是关于对象初始化优先级的主要内容,如果未能解决你的问题,请参考以下文章