是什么让Enum课程无法获得? [英] What makes the Enum class uninheritable?

查看:64
本文介绍了是什么让Enum课程无法获得?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注 <的源代码code>枚举类。它看起来像是一个带有受保护构造函数的普通抽象类。它不是最终的,它内部没有任何特殊的注释,也不使用本机代码。然而,它不能直接子类化。实际上,以下代码无法编译:

I've been looking at the source code of the Enum class. It seems like a plain abstract class with a protected constructor to me. It's not final, it doesn't have any special annotations inside it and it doesn't use native code. And yet, it cannot be subclassed directly. In fact, the following code doesn't compile:

class Foo<E extends Enum<E>> extends Enum<E> {
    Foo(String name, int ordinal) {
        super(name, ordinal);
    }
}

我知道枚举是Java中的一个特殊类,我理解为什么有必要禁止直接子类化。但从技术上讲,你如何执行这种行为?
程序员是否可以创建一个类似的非final类,尽管有一个可访问的构造函数但不允许直接子类化?

I know that Enum is a special class in Java and I understand that there are good reasons why direct subclassing should be forbidden. But technically, how do you enforce this behavior? Can a programmer create a similar non-final class that wouldn't allow direct subclassing despite having an accessible constructor?

推荐答案

仅在语言中直接扩展枚举无效。每次声明枚举时, 都会创建 Enum 的子类。

It's only invalid to extend Enum directly within the language. Any time you declare an enum, that does create a subclass of Enum.

JLS阻止您手动声明扩展 Enum 的类的方式只是明确地禁止它。来自 JLS第8.1.4节

The way the JLS prevents you from "manually" declaring a class which extends Enum is simply to prohibit it explicitly. From JLS section 8.1.4:


如果ClassType命名类Enum或对其进行任何调用,则为编译时错误。

It is a compile-time error if the ClassType names the class Enum or any invocation of it.

(其中 ClassType 是您要扩展的类型。)

(Where ClassType is the type you're extending.)

如果没有这个规则,你的代码就完全有效了。

Without that rule, your code would have been perfectly valid.

这篇关于是什么让Enum课程无法获得?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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