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 ?
An enumerated property is one that can take a value from a predefined list of values.
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).
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With