gpt4 book ai didi

java - java中为什么限制在内部类中声明静态成员变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:42 25 4
gpt4 key购买 nike

考虑下面的例子 在内部类中继承静态变量没有任何限制,为什么我们在内部类中只能声明静态成员变量?

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;

}

可以通过继承限制内部类中的静态变量的原因是什么?我是否遗漏了一些非常基本的东西?

最佳答案

来自甲骨文网站:

  1. As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.
  1. Because an inner class is associated with an instance, it cannot define any static members itself.

我是这样理解的:

如果内部类有自己的静态字段,静态字段必须在类实例化之前初始化;

但是一个内部类只存在一个外部类的实例,所以它不能在实例化之前初始化它的静态成员,然后在矛盾中。

关于java - java中为什么限制在内部类中声明静态成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21019208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com