考慮下面的例子 爲什麼我們限制在內部類中聲明靜態成員變量時對內部類中繼承靜態變量沒有任何限制?爲什麼我們被限制在java的內部類中聲明靜態成員變量?
public class Outer {
public class Inner {
public static String notAllowed;
/* Above line give following compilation error
The field notAllowed cannot be declared static in a non-static inner type, unless initialized with a constant expression
*/
}
}
但是現在如果我的內部類擴展了包含靜態變量的其他類,則此工作正常。 考慮下面的代碼:
public class Outer {
public class Inner extends InnerBase {
/* Since it extends InnerBase so we can access Outer.Inner.allowed */
public Inner(){
Outer.Inner.allowed = null; // Valid statement
}
}
}
public class InnerBase {
public static String allowed;
}
那麼究竟是什麼在內部類限制靜態變量的原因,它是通過繼承實現的? 我是否缺少一些非常基本的東西?
因爲'Inner'類定義本身不是靜態的嗎? –
http://stackoverflow.com/questions/1953530/why-does-java-prohibit-static-fields-in-inner-classes –
注意,在你的第二個例子中,你沒有聲明一個'static' 'Inner'中的字段,你只是簡單的給它賦值。 –