For an enumeration defined in a class, like
class OuterClass {
public enum Method {
GET,
PUT,
POST,
DELETE;
}
}
Is the enumeration a static nested class (https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)? It seems to be the case judging from the syntax used to refer to it. Or is it a non-static nested class (an inner class)?
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).
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
So the first thing that I thought was using an Enum to store all the naming there and easily access them. Unfortunately, it turned out that Enums are actually not that flexible. Meaning that you can't have nested or multi-level Enums.
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.
The JLS says
An enum declaration specifies a new enum type, a special kind of class type.
So it looks like the word from Oracle is that enums are classes.
If you declare an enum inside another class, then yes, it's an inner class. And enums are always static, so yes, it's fair to call an enum a static inner class (or nested class) when it's declared in another class.
As per §8.9 of the JLS:
An enum declaration specifies a new enum type, a special kind of class type.
[...]
A nested enum type is implicitly
static
. It is permitted for the declaration of a nested enum type to redundantly specify thestatic
modifier. [...]
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