在Java中,when是枚举常量的构造函数是否被调用? [英] In Java, when is the constructor for an enumerated constant invoked?

查看:125
本文介绍了在Java中,when是枚举常量的构造函数是否被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Java中使用一个设计的例子,下面是代码:

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());
}

问题是:
在Java中,when是构造函数一个枚举常量调用?在上面的例子中,我只使用 Save 枚举常量。这是否意味着构造函数只被调用一次以创建 Save ?或者保存文件可以一起构造吗?

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?

推荐答案

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.

这篇关于在Java中,when是枚举常量的构造函数是否被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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