FreshAir
FreshAir

Reputation: 301

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

Upvotes: 6

Views: 993

Answers (3)

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16276

The generated bytecode for the enum declaration is as follows:

// compiled from: OuterClass.java
public final static enum INNERCLASS ...

So yes, enum is a static nested class in this case - confirmation in the JLS.

Upvotes: 3

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

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.

Upvotes: 7

Turing85
Turing85

Reputation: 20205

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. [...]

Upvotes: 4

Related Questions