0
public enum Device {

  ON, OFF, STANDBY;

  private Device() {
    System.out.println("Hello!");
  }
}

public static void main(String[] args) {
  Device d = Device.STANDBY;
}

Why does this code print out three times Hello! Hello! Hello! ?

How do constructors get invoked at all in an enumeration class if it is private?

gi004
  • 1
  • 2
  • 1
    Because you have three ENUM declarations? – papaya Feb 14 '20 at 14:41
  • Does this answer your question? [In java, What does such enum type compile to?](https://stackoverflow.com/questions/31039980/in-java-what-does-such-enum-type-compile-to) – papaya Feb 14 '20 at 14:43
  • 2
    Because `Device` instances are objects, not primitive values, so the `Device` constructor is invoked when they are instantiated. The fact that the constructor is `private` is irrelevant; it is not invoked from outside of the `enum` itself. In fact, `enum` constructors [are always private](https://stackoverflow.com/a/7748220/12299000) even if you don't declare that explicitly. – kaya3 Feb 14 '20 at 14:44
  • it's like `Device ON = new Device(); Device OFF = new Device();` and so on/off – fantaghirocco Feb 14 '20 at 14:54

0 Answers0