非公開類Out
中的靜態初始化塊不運行,但運行靜態嵌套類snOut
中的靜態初始化塊。如何以及爲什麼這可能?靜態初始化塊跳過
public class staticNested {
static{
System.out.println("In staticNested");
}
static class sn{
static{
System.out.println("sn in staticNested");
}
void p(){
System.out.println("In static nested class method p");
}
}
public static void main(String [] args){
sn n = new sn();
n.p();
Out.snOut no = new Out.snOut();
no.p();
}
}
class Out{
static{
System.out.println("In Out"); //Skips this
System.out.println("Here"); //Skips this
}
static class snOut{
static {
System.out.println("In snOut in Out");
}
private int x;
void p(){
System.out.println("In snOut in outside Class out: " + x);
}
}
}
這是輸出:
In staticNested
sn in staticNested
In static nested class method p
In snOut in Out
In snOut in outside Class out: 0
我不認爲班級'Out'會被加載。它在您訪問其靜態字段或靜態方法或加載實例時加載。我的初學者知識> – jn1kk
啊。我懂了。在主要方法中創建一個新實例會使塊運行。謝謝 – Mob
爲什麼'Out'不加載和'staticNested'確實是因爲main是在'staticNested'中,它可以像你期望的那樣自動加載。 – jn1kk