考虑下面的例子为什么在内部类中继承静态变量没有任何限制时,我们被限制在内部类中声明静态成员变量?
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; }
那么在内部类中限制静态变量的原因是什么,因为它可以通过继承来实现?我错过了非常基本的东西吗?