是什么使得Java中的枚举不可实例化? [英] What makes enum in java non instantiable?
问题描述
我知道一个枚举
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();
}
当我尝试实例化枚举(不是类)时,出现编译时错误:
When I tried to instantiate enum (not class) I got compile time error as:
error: enum types may not be instantiated
Year y = new Year();
据我所知,私有构造函数使类不可实例化。我认为编译器提供了一个私有构造函数。但是当我看到我们可以使用默认修饰符为枚举定义构造函数而仍然无法创建枚举类型的对象时,我又感到困惑。
As per my knowledge a private constructor makes a class non instantiable. And I thought that compiler is providing a private constructor. But again I got confused when saw we can define a constructor for enum with default modifier and still cannot create an object of type enum.
enum Year
{
First, Second, Third, Fourth;
Year()
{
}
}
class Example
{
public static void main(String[] args)
{
Year y = new Year();
}
}
我的疑问是,如果这与构造函数无关,那么是什么使Java中的枚举无法实例化?
My doubt is, if it is not about constructors then what makes enum in Java non instantiable?
推荐答案
它在 Java语言规范:
< a href = https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9 rel = noreferrer> 8.9。枚举类型
...
枚举类型除了由其枚举常量定义的实例外,没有其他实例。尝试显式实例化枚举类型(第15.9.1节)是编译时错误。
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).
因此,编译器确保满足此要求。由于编译器知道,因此编译器不知道。类型为枚举
,它可以区分枚举Year
和最终类Year
。
Hence the compiler ensures that this requirement is met. Since the compiler "knows" that the type is an enum
, it can distinguish between enum Year
and final class Year
.
此外,枚举构造函数不允许使用访问修饰符:
Also, no access modifier is allowed for an enum constructor:
...
如果枚举声明中的构造函数声明为public或
It is a compile-time error if a constructor declaration in an enum declaration is public or protected.
...
在枚举声明中,没有访问修饰符的构造函数声明是私有的。
因此,在实践中,枚举
构造函数看起来像包作用域(无访问修饰符),
So, in practice, an enum
constructor looks like package-scoped (no access modifier), but it really is private.
最后,同一部分还声明了
Finally, the same section also states
在没有构造函数声明的枚举声明中,则隐式声明默认构造函数。 默认构造函数为private ,没有正式参数,没有throws子句。
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.
这使得枚举
不可实例化,即使未显式声明任何构造函数。
This makes the enum
non-instantiable even if no constructor is explicitly declared.
这篇关于是什么使得Java中的枚举不可实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!