아래 예제를 고려하십시오 내부 클래스의 정적 변수 상속에 제한이없는 경우 내부 클래스의 정적 멤버 변수를 선언하도록 제한하는 이유?자바의 내부 클래스에서 정적 멤버 변수를 선언하도록 제한되는 이유는 무엇입니까?
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의 복제본 –
두 번째 예에서 '정적' 필드의 값을 지정하면됩니다. –