wantToLearn
wantToLearn

Reputation: 491

enum properties & side effects

I have a question regarding enum (it might be a simple one but ....). This is my program:

public class Hello { 
         public enum MyEnum 
         { 
               ONE(1), TWO(2); 
               private int value; 
               private MyEnum(int value) 
               { 
                    System.out.println("hello");  
                    this.value = value; 
               } 
               public int getValue() 
               { 
                    return value; 
               } 
        } 
        public static void main(String[] args)  
        { 
              MyEnum e = MyEnum.ONE; 
        } 
}

and my question is: Why the output is

hello
hello

and not

hello ?

How the code is "going" twice to the constructor ? When is the first time and when is the second ? And why the enum constructor can not be public ? Is it the reason why it print twice and not one time only ?

Upvotes: 23

Views: 1120

Answers (3)

Michael Kazarian
Michael Kazarian

Reputation: 4462

How the code is "going" twice to the constructor ?

Conctructor is invoked for each element of enum. Little change your example for demonstration it:

public class Hello { 
    public enum MyEnum { 
        ONE(1), TWO(2); 
        private int value; 
        private MyEnum(int value) { 
            this.value = value;
            System.out.println("hello "+this.value);  
        } 
        public int getValue() { 
            return value; 
        } 
    } 
    public static void main(String[] args) { 
        MyEnum e = MyEnum.ONE; 
    } 
}

Output:

hello 1
hello 2

Upvotes: 11

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Your constructor invoke twice. The moment of loading your Enum class it will invoke number of time which equals to number of enum types here.

 MyEnum e = MyEnum.ONE; // singleton instance of Enum

consider following

public class Hello {

public enum MyEnum
{
    ONE(1), TWO(2), THREE(3);
    private int value;
    private MyEnum(int value)
    {
        System.out.println("hello"+value);
        this.value = value;
    }
    public int getValue()
    {
        return value;
    }
}
public static void main(String[] args)
{
    MyEnum e = MyEnum.ONE;
}

}

Out put

hello1
hello2
hello3

Upvotes: 3

piet.t
piet.t

Reputation: 11911

Enums are Singletons and they are instanciated upon loading of the class - so the two "hello"s come from instanciating MyEnum.ONE and MyEnum.TWO (just try printing value as well).

This is also the reason why the constuctor must not be public: the Enum guarantees there will ever only be one instance of each value - which it can't if someone else could fiddle with the constructor.

Upvotes: 29

Related Questions