KrawallKurt
KrawallKurt

Reputation: 471

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

Upvotes: 0

Views: 159

Answers (2)

Michael Kazarian
Michael Kazarian

Reputation: 4462

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.

Upvotes: 3

user2575725
user2575725

Reputation:

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

Upvotes: 0

Related Questions