靜態塊、例項塊、建構函式執行順序
阿新 • • 發佈:2018-11-19
靜態塊、例項塊、建構函式的執行順序:
1.先執行靜態方法塊
2.再執行例項方法塊
3. 再執行建構函式塊
同一個類下不管new多少次,該類下的靜態塊只執行一次(但是一次可以執行多個)
不管是new幾個類,所有的類都先執行靜態方法快,(執行完所有類的靜態塊後)再執行例項方法快,再執行建構函式
public class Kuai { public static void main(String[] args) { KuaiTest t = new KuaiTest(); KuaiTest t1 = new KuaiTest("名字"); KuaiTest t2 = new KuaiTest("18"); } } class KuaiTest{ private String name; private int id; public KuaiTest() { System.out.println("構造方法"); } public KuaiTest(String name) { this.name = name; System.out.println(this.name); } public KuaiTest(int id) { this.id = id; System.out.println(this.id); } static { System.out.println("靜態方法塊1"); } static{ System.out.println("靜態方法塊2"); } { System.out.println("例項方法塊1"); } { System.out.println("例項方法塊2"); } }
執行結果:
一個類可以有多個靜態方法塊、例項塊、建構函式。
public class A {
static {
System.out.println("A類的靜態塊");
}
public A() {
System.out.println("A類的建構函式塊");
}
{
System.out.println("A類的例項方法塊");
}
}
public class B extends A{ static { System.out.println("B類的靜態塊"); } public B() { System.out.println("B類的建構函式塊"); } { System.out.println("B類的例項方法塊"); } public static void main(String[] args) { A a = new A(); System.out.println("--------------------"); A b = new B(); System.out.println("--------------------"); B c = new B(); } }