Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums defined in a class is a static nested class?

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

like image 539
FreshAir Avatar asked Jun 10 '18 19:06

FreshAir


People also ask

Is enum class static?

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

Can you define an enum within a class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can enums be nested?

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.

Are enum methods 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.


2 Answers

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.

like image 146
Dawood ibn Kareem Avatar answered Oct 14 '22 01:10

Dawood ibn Kareem


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 the static modifier. [...]

like image 4
Turing85 Avatar answered Oct 14 '22 02:10

Turing85