java中的初始化顺序
public class Person { public String name="Person"; int age=0; { System.out.println("初始化块:"+name); name = "initBlock"; System.out.println("初始化块:"+name); } public Person(){ name="constrcutor"; System.out.println("构造器:"+name); } } public class Child extends Person { public String grade; public static void main(String[] args) { Person p = new Child(); System.out.println(p.name); } }
运行结果:
初始化块:Person
初始化块:initBlock
构造器:constrcutor
constrcutor
总结:
1.定义变量时的赋值最先被执行
2.在初始化块进行的赋值其次被执行
3.在构造方法中的赋值最后被执行
原文链接:https://blog.csdn.net/qq_28193019/article/details/72638936