Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
John Assymptoth Avatar asked Jan 20 '11 00:01

John Assymptoth


People also ask

Can enum extend another enum in Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

Can we add constants to enum?

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).

Is it better to use enum or constant?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.


1 Answers

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.

like image 117
ide Avatar answered Nov 11 '22 13:11

ide