優先級從高到低 | 類別 | 是否執行只執行一次 |
1 | 靜態成員變量 | 只在類第一次被加載時執行一次 |
靜態太代碼塊 |
2 | 普通成員變量 | 每次創建類的對象時都執行 |
普通代碼快 |
3 | 構造方法 | 每次創建類的對象時都執行 |
**同優先級的按照出現順序依次執行** |
import org.junit.Test;
public class FuckFilterTest {
@Test
public void shunxu() {
classB b = new classB();
System.out.println("-------------------");
classB b2 = new classB();
}
}
class classB {
public classB() {
System.out.println("構造方法");
}
private static classA s1 = new classA("靜態成員變量1");
private classA f1 = new classA("普通成員變量1");
{
System.out.println("構造代碼塊1");
}
static {
System.out.println("靜態塊1");
}
{
System.out.println("構造代碼塊2");
}
private classA f2 = new classA("普通成員變量2");
private static classA s2 = new classA("靜態成員變量2");
static {
System.out.println("靜態塊2");
}
}
class classA {
classA(String desc) {
System.out.println(desc);
}
}
靜態成員變量1
靜態塊1
靜態成員變量2
靜態塊2
普通成員變量1
構造代碼塊1
構造代碼塊2
普通成員變量2
普通成員變量1
構造代碼塊1
構造代碼塊2
普通成員變量2
構造方法