在Java中,什么时候调用枚举常量的构造函数?
要在 Java 中使用一个人为的示例,代码如下:
enum Commands{
Save("S");
File("F");
private String shortCut;
private Commands(String shortCut){ this.shortCut = shortCut; }
public String getShortCut(){ return shortCut; }
}
我有以下测试/驱动程序代码:
public static void main(String args[]){
System.out.println(Commands.Save.getShortCut());
}
问题是: 在Java中,什么时候调用枚举常量的构造函数?在上面的示例中,我仅使用 Save
枚举常量。这是否意味着构造函数被调用一次来仅创建 Save
?或者无论如何,Save
和 File
都会一起构造吗?
To use a contrived example in Java, here's the code:
enum Commands{
Save("S");
File("F");
private String shortCut;
private Commands(String shortCut){ this.shortCut = shortCut; }
public String getShortCut(){ return shortCut; }
}
I have the following test/driver code:
public static void main(String args[]){
System.out.println(Commands.Save.getShortCut());
}
The question is:
In Java, when is the constructor for an enumerated constant invoked? In the above example, I am only using the Save
enumerated constant. Does this mean that the constructor is called once to create Save
only? Or will both Save
and File
be constructed together regardless?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
初始化
enum
类时会调用构造函数。每个构造函数都将按照成员声明顺序被调用,无论实际引用和使用哪些成员。The constructors are invoked when the
enum
class is initialized. Each constructor will be invoked, in member declaration order, regardless of which members are actually referenced and used.与
static() {...}
方法非常相似,构造函数在 Enum 类首次初始化时被调用。枚举的所有实例都是在使用任何实例之前创建的。在此示例中,
Save
和File
的构造函数将在调用Save.getShortCut()
之前完成。正如代码中所声明的那样,它们是按顺序调用的。
Much like the
static() {...}
method, the constructors are invoked when the Enum class is first initialized. All instances of the Enum are created before any may be used.In this sample, the ctor for both
Save
andFile
will have completed beforeSave.getShortCut()
is invoked.They are invoked sequentially, as declared in the code.
正如其他人所说,两者都将在类初始化时创建。我想指出的是,这是在任何静态初始化程序之前完成的,因此您可以在静态块中使用这些枚举。
Both will be created at the class initialization time as others said. I like to point out that this is done before any static initializers so you can use these enums in static block.