靜態變量分析一些奇怪的場景在以下靜態塊:的java:訪問內部靜態塊
static {
System.out.println("Inside Static Block");
i=100; // Compilation Successful , why ?
System.out.println(i); // Compilation error "Cannot reference a field before it is defined"
}
private static int i=100;
雖然相同的代碼工作正常同時使用:
static {
System.out.println("Inside Static Block");
i=100; // Compilation Successful , why ?
System.out.println(MyClass.i); // Compiles OK
}
private static int i=100;
不知道爲什麼變量初始化不需要使用類名的變量訪問,而SOP需要?
您是不是要在兩個塊中顯示錯誤? – Bohemian
@Bohemian我認爲這是一個複製/粘貼失敗。第二個塊不應該顯示錯誤。 –
另請參閱http://stackoverflow.com/questions/15820302/recursive-initializer-works-when-i-add-this – ZhongYu