Search code examples
javaenumsqualified-name

In Java, why is it possible to qualify an Enum Constant with another Enum Constant?


Recently, I've noticed, it is possible to have:

class Test {
    public enum Season { WINTER, SPRING, SUMMER, FALL }
    Season field = Season.WINTER.SPRING; // why is WINTER.SPRING possible?
}

Is there a reason for this?


Solution

  • When you access a static member of an object (including enums) in Java, the compiler effectively replaces the object with its static type. More concretely,

    class ExampleClass {
        static int staticField;
        static void staticMethod() {
            ExampleClass example = new ExampleClass();
            example.staticField;     // Equivalent to ExampleClass.staticField;
            example.staticMethod();  // Equivalent to ExampleClass.staticMethod();
        }
    }
    

    Similarly, since enums are effectively "static", Season.WINTER.SPRING is equivalent to Season.SPRING; Season.WINTER is replaced with its enum type Season.

    As a side note, accessing static members from instances is discouraged because it can be quite confusing. For example, if you saw a piece of code that contained someThread.sleep(), you might be tricked into believing that someThread is put to sleep. However, since sleep() is static, that code is actually invoking Thread.sleep() which sleeps the current thread.