Directly on the code
public class Study {
public Study(){//构造方法
System.out.println("init");
}
{//构造代码块
System.out.println("hehe");
}
static {//静态代码块
System.out.println("haha");
}
public static void main(String[] args) {
Study s1 = new Study();
Study s2 = new Study();
}
}
Results of the
Conclusions: 1) and the static block of code execution priority is executed only once. 2) configured to perform block constructor priority, and each method call the constructor will be executed.
In the case of inheritance
public class Study {
public Study(){//构造方法
System.out.println("老子构造方法");
}
{//构造代码块
System.out.println("老子构造代码块");
}
static {//静态代码块
System.out.println("老子静态代码块");
}
public static void main(String[] args) {
Study s1 = new Study1();
Study s2 = new Study1();
}
}
class Study1 extends Study{
public Study1(){//构造方法
System.out.println("儿子构造方法");
}
{//构造代码块
System.out.println("儿子构造代码块");
}
static {//静态代码块
System.out.println("儿子静态代码块");
}
}
Conclusions: 1) static code block will always take precedence. 2) the parent building block Constructor priority subclass building block constructor.
Reproduced in: https: //my.oschina.net/kalnkaya/blog/1842039