Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum properties & side effects

Tags:

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 ?

like image 354
wantToLearn Avatar asked Dec 03 '13 07:12

wantToLearn


People also ask

What is an enum property?

An enumerated property is one that can take a value from a predefined list of values.

Can enums have attributes?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Can enums have fields?

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.

What is enum used for?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


Video Answer


1 Answers

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.

like image 146
piet.t Avatar answered Oct 13 '22 11:10

piet.t