如何在枚举中使用构造函数?

时间:2014-06-27 09:28:50

标签: java constructor enums singleton

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

public enum mySingleton implements myInterface {

    INSTANCE;
    private final myObject myString;

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

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

2 个答案:

答案 0 :(得分:3)

你的枚举错了。以下正确声明:

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

为枚举的每个元素调用Conctructor。

答案 1 :(得分:0)

你可以试试这个:

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