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?
No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.
4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.
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).
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.
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.
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