简体   繁体   中英

How to use constructor in enum?

I want to use an enum to create a singleton class in java. Should look like this:

public enum mySingleton implements myInterface {

    INSTANCE;
    private final myObject myString;

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

Looks like I cannot use any parameters in the constructor. Is there any workaround for this? Thanks in advance

Yor enum is wrong. Below correct declaration:

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

Output:

One value
Two value

Conctructor is invoked for each element of enum.

You can try this:

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.");
   }
}

Also see more demos

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM