先看一段代碼:
package com.wjj.test;
/**
* @author 作者 : 榨菜哥
* @createTime 創(chuàng)建時間:2018年7月27日 下午3:26:47
* @discription 類說明:
* @version 版本:
*/
public class ConstructorTest {
public static void main(String[] args) {
Dog dog = new Dog();
}
}
class Animal {
String name;
int age;
public Animal() {
System.out.println("Animal 類");
}
{
System.out.println("Animal 代碼塊");
}
static {
System.out.println("Animal static塊");
}
}
class Dog extends Animal {
public Dog() {
System.out.println("Dog 類");
}
{
System.out.println("Dog 代碼塊");
}
static {
System.out.println("Dog static 塊");
}
}
執(zhí)行上面代碼輸出結(jié)果:
Animal static塊
Dog static 塊
Animal 代碼塊
Animal 類
Dog 代碼塊
Dog 類
總結(jié):
static代碼塊、代碼塊、構(gòu)造函數(shù)的執(zhí)行順序為:
父類static代碼塊 > 子類static代碼塊 > 父類代碼塊 > 父類構(gòu)造函數(shù) > 子類代碼塊 > 子類構(gòu)造函數(shù)
(每創(chuàng)建一個對象,就會執(zhí)行一次非靜態(tài)代碼塊)