Device states

We consider an enum describing device states:

Device state enumeration Main method Result
public enum Device {

  ON, OFF, STANDBY;

  private Device() {
    System.out.println("Hello!");
  }
}
public static void main(String[] args) {
  Device d = Device.STANDBY;
}
Hello!
Hello!
Hello!

Answer the following questions:

  • The Device() constructor is being declared private so how does it get invoked at all?

  • Why do we see "Hello!" three times on output though only Device.STANDBY shows up in the current example's main(...) method?

Solution

ON, OFF and STANDBY are static references to Device instances being created inside our enum Device class. This happens the way being described in Figure 361, “Define a private Day constructor ”.

Thus our private constructor in question is being called from within enum Device class scope and therefore not being limited by access restrictions.