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). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
As enums are inherently static , there is no need and makes no difference when using static-keyword in enums . If an enum is a member of a class, it is implicitly static.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.
Yes, nested enums are implicitly static.
From the language specification section 8.9:
Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.
It wouldn't make sense to make an instance-level (non-static) inner enum class - if the enum instances were themselves tied to the outer class they'd break the enum guarantee -
e.g. if you had
public class Foo {
private enum Bar {
A, B, C;
}
}
For the enum values to properly act as constants, (psuedocode, ignoring access restrictions)
Bar b1 = new Foo().A
Bar b2 = new Foo().A
b1 and b2 would have to be the same objects.
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