java - 为什么允许在非静态内部类中将编译时常量设为静态?

标签 java static inner-classes

假设我们有如下代码。

public class Outer{
    class Inner{
        public static final String s = "abc";
    }
    static class Nested{
        public static final SomeOtherClass instance = new SomeOtherClass();
    }
} 

我明白要实例化非静态内部类的对象需要外部类的对象static 表示类相关,访问它不需要实例化对象。非静态内部类只有在我们实例化了外部类的对象后才能使用。在其中包含任何静态引用可能没有意义。

我的问题:

  1. 非静态内部类可以在没有外部类的任何显式对象的情况下加载吗?

  2. 为什么编译时间常量(字符串文字,因为它们在字符串池和原始类型中以特殊方式处理)在 static 中被允许strong>非静态内部类 ?

编辑:为什么不能将非编译时常量设为静态,我知道这是根据 JLS,但只是想知道会出现什么问题,制定此规则的目的是什么。

最佳答案

  1. Can non static inner class get loaded without any explicit object of Outer class ?

是的。创建内部类的实例需要外部类的实例。但是这两个类都可以在创建任何实例之前加载。

  1. 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/

相关文章:

java - 如何计算商会号码之间的相似度?

java - 智能转换为 'ObserverT!!' 是不可能的,因为 'item.get()' 是一个复杂的表达式

java - 如何在运行更新 View 的后台服务时访问 Activity 的 View 对象

c++ - 编译器如何实现静态变量初始化?

java - final 在 Java 中做什么? - 困难版

java - 通过 CMIS 标准实现注销

java - 当我平移 map 时,Google map 叠加层不会移动

c++ - Qt 文件太大。

java - 在java中使用内部类扩展类(并且从一个类到另一个类时也扩展内部类)

java - 为什么扩展内部类的本地类不能访问内部类封闭实例?