gpt4 book ai didi

java - 什么使 java 中的枚举不可实例化?

转载 作者:太空狗 更新时间:2023-10-29 23:03:28 25 4
gpt4 key购买 nike

我知道一个枚举

enum Year
{
First, Second, Third, Fourth;
}

转换成

final class Year extends Enum<Year>
{
public static final Year First = new Year();
public static final Year Second = new Year();
public static final Year Third = new Year();
public static final Year Fourth = new Year();
}

当我尝试实例化枚举(不是类)时,出现编译时错误:

error: enum types may not be instantiated
Year y = new Year();

据我所知,私有(private)构造函数使类不可实例化。我认为编译器提供了一个私有(private)构造函数。但是当我看到我们可以使用 default 修饰符为枚举定义构造函数并且仍然不能创建枚举类型的对象时,我再次感到困惑。

enum Year
{
First, Second, Third, Fourth;
Year()
{
}
}

class Example
{
public static void main(String[] args)
{
Year y = new Year();
}
}

我的疑问是,如果它不是关于构造函数那么是什么让 Java 中的枚举不可实例化?

最佳答案

它在 Java Language Specification 中指定:

8.9. Enum Types

...

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).

因此编译器确保满足这个要求。由于编译器“知道”类型是 enum,因此它可以区分 enum Yearfinal class Year

此外,枚举构造函数不允许使用访问修饰符:

8.9.2. Enum Body Declarations

...

It is a compile-time error if a constructor declaration in an enum declaration is public or protected.

...

In an enum declaration, a constructor declaration with no access modifiers is private.

因此,在实践中,enum 构造函数看起来像包作用域(没有访问修饰符),但它实际上是私有(private)的。

最后,同一节还说

In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause.

这使得 enum 不可实例化,即使没有显式声明构造函数也是如此。

关于java - 什么使 java 中的枚举不可实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36709719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com