为什么在 Java 16 中的非静态内部 class 中允许使用静态方法?

Why are static methods allowed inside a non-static inner class in Java 16?

我们知道一个非静态的内部class可以使用外部class的实例来访问,所以静态方法在非静态class内部的意义不大.但是从 Java 开始,在非静态内部 class.

中允许使用 16 个静态方法

最初为什么会有这个限制?为什么在较新的版本中允许这样做?

public class OuterClass {

    class InnerClass {
        static void printMe() {
            System.out.println("Inside inner class");
        }
    }

    public static void main(String[] args) {
        InnerClass.printMe();
    }

}

您要求对 Java 16 中的更改进行推理,因此您应该首先检查 Release Notes 以查看它是否有任何内容。它确实:

JEP 395: Records (JDK-8246771)
tools/javac
Records have been added to the Java language. Records are a new kind of class in the Java language. They act as transparent carriers for immutable data with less ceremony than normal classes.

Since nested classes were first introduced to Java, with the exception of static final fields initialized by constant expressions, nested class declarations that are inner have been prohibited from declaring static members. This restriction applies to non-static member classes, local classes, and anonymous classes.

JEP 384: Records (Second Preview) added support for local interfaces, enum classes, and record classes, all of which are static definitions. This was a well-received enhancement, permitting coding styles that reduce the scope of certain declarations to local contexts.

While JEP 384 allowed for static local classes and interfaces, it did not relax the restriction on static member classes and interfaces of inner classes. An inner class could declare a static interface inside one of its method bodies, but not as a class member.

As a natural next step, JEP 395 further relaxes nesting restrictions, and permits static classes, methods, fields, etc., to be declared within inner classes.

For further details, see JEP 395.

具体推理见JEP 395

Static members of inner classes

It is currently specified to be a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable. This means that, for example, an inner class cannot declare a record class member, since nested record classes are implicitly static.

We relax this restriction in order to allow an inner class to declare members that are either explicitly or implicitly static. In particular, this allows an inner class to declare a static member that is a record class.

换句话说,有必要针对特定​​情况取消对内部classes 的静态成员的限制;即允许 record classes 在内部 classes 中声明。但他们决定趁机取消所有情况下的限制。

这意味着 设计者 已经得出结论,原始限制作为一个整体既不是技术原因所必需的,也是不可取的。


why did this restriction exist in the first place?

这是一个更难的问题。做出该限制的决定是在 1996 年或 1997 年初设计 Java 1.1 时做出的。不太可能有人还能准确记住最初决定背后的原因。所以除非有人能找到同时代的书面资料,否则我们永远无法确定。

(Brian Goetz 在上面评论道:“...在添加 nested 的时候(Java 1.1),在另一个 class,所以这个问题被推迟了。”。这当然有道理,但这可能(只是)一个人对 25 年前发生的事情的回忆。如果是我,我不会不太相信我的记忆力。除非我有当时的会议记录、笔记等可供参考。)

这里有一些关于原始限制的基本原理的猜测: