假设我们有如下代码。
public class Outer{
class Inner{
public static final String s = "abc";
}
static class Nested{
public static final SomeOtherClass instance = new SomeOtherClass();
}
}
我明白要实例化非静态内部类的对象需要外部类的对象。 static
表示类相关,访问它不需要实例化对象。非静态内部类只有在我们实例化了外部类的对象后才能使用。在其中包含任何静态引用可能没有意义。
我的问题:
非静态内部类可以在没有外部类的任何显式对象的情况下加载吗?
为什么编译时间常量(字符串文字,因为它们在字符串池和原始类型中以特殊方式处理)在 static 中被允许strong>非静态内部类 ?
编辑:为什么不能将非编译时常量设为静态,我知道这是根据 JLS,但只是想知道会出现什么问题,制定此规则的目的是什么。
最佳答案
- Can non static inner class get loaded without any explicit object of Outer class ?
是的。创建内部类的实例需要外部类的实例。但是这两个类都可以在创建任何实例之前加载。
- Why can we have compile time constants (String literals, as they are handled in special way in String pool and primitive types) are allowed to be made static in non static inner class ?
语言规范允许对常量变量进行此异常(exception)处理。来自Java Language Specification, section 8.1.3: "Inner classes and enclosing instances" :
It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).
并且字符串变量可以是常量,因为4.12.4, "final
Variables" 节:
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).
关于java - 为什么允许在非静态内部类中将编译时常量设为静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510433/