【问题标题】:How to use constructor in enum?如何在枚举中使用构造函数?
【发布时间】:2014-06-27 09:28:50
【问题描述】:

我想使用枚举在 java 中创建一个单例类。应该是这样的:

public enum mySingleton implements myInterface {

    INSTANCE;
    private final myObject myString;

    private mySingleton(myObject myString) {
        this.myString= myString;
    }
}

看起来我不能在构造函数中使用任何参数。有什么解决方法吗?提前致谢

【问题讨论】:

  • 好的,我明白了。如果我有一个更复杂的对象怎么办?我只是编辑问题..

标签: java constructor enums singleton


【解决方案1】:

你的枚举是错误的。下面是正确的声明:

public class Hello { 
    public enum MyEnum { 
            ONE("One value"), TWO("Two value"); //Here elements of enum.
            private String value; 
            private MyEnum(String value) { 
                this.value = value;
                System.out.println(this.value);  
            } 
            public String getValue() { 
                return value; 
            } 
    }
public static void main(String[] args) { 
        MyEnum e = MyEnum.ONE; 
    } 
}

输出:

One value
Two value

为枚举的每个元素调用构造函数。

【讨论】:

  • 我编辑了我的问题。它不是我拥有的字符串,而是更复杂的对象。我想保存对此的引用。
  • @KrawallKurt 您可以使用任何对象作为构造函数 arg。但是,它必须在编译时静态知道,因此 - 根据您的用例 - 枚举可能不是正确的选择。
  • 好的,谢谢。我只是用另一个枚举尝试过。我该怎么做?像 INSTANCE(myEnum); ?
【解决方案2】:

你可以试试这个:

enum Car {
   lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
   private int price;
   Car(int p) {
      price = p;
   }
   int getPrice() {
      return price;
   } 
}
public class Main {
   public static void main(String args[]){
      System.out.println("All car prices:");
      for (Car c : Car.values())
      System.out.println(c + " costs " 
      + c.getPrice() + " thousand dollars.");
   }
}

另见more demos

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多