为什么允许编译时常量在非静态内部类中变为静态? [英] Why compile time constants are allowed to be made static in non static inner classes?

查看:389
本文介绍了为什么允许编译时常量在非静态内部类中变为静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们的代码如下所示。

Suppose we have code as below.

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

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

I understand to instantiate object of non static inner classes an object of Outer class is needed. static means class related and for accessing it an object is not required to be instantiated. Non static inner class can only be used once we have an object of Outer class instantiated. Having any static references in it may not make sense.

我的问题:


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

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

为什么编译时间常量(字符串文字,因为它们在字符串中以特殊方式处理允许在非静态内部类静态

Why 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 ?

编辑:为什么不允许非编译时间常数变为静态,我知道它是按照JLS,但只是想知道会出现什么问题,意图是什么制定此规则。

Edit : Why can not non compile time constants be allowed to be made static, I know its as per JLS, but just wish to know what would have gone wrong, what was the intent to make this rule.

推荐答案



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


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

Yes. Creating an instance of an inner class requires an instance of the outer class. But both classes can be loaded before any instances are created.



  1. 为什么我们可以拥有编译时常量(字符串文字,因为它们在字符串池和基元类型中以特殊方式处理)允许在非静态内部类中保持静态?


语言规范允许常量变量的此异常。来自 Java语言规范,部分8.1.3:内部类和封闭实例

The language specification allows this exception for constant variables. From the Java Language Specification, section 8.1.3: "Inner classes and enclosing instances":


如果是一个编译时错误内部类声明一个显式或隐式静态的成员,除非该成员是一个常量变量(§4.12.4)。

字符串变量可以是常量,因为部分 4.12.4, final 变量

And String variables can be constants, because of section 4.12.4, "final Variables":


常量变量是基本类型或类型String的最终变量,用常量表达式初始化(​​§15.28)。

这篇关于为什么允许编译时常量在非静态内部类中变为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆