Laith Zeyad
Laith Zeyad

Reputation: 45

How does the body of the below java enum class work?

public enum ID {
 Player(),
 Enemy();
}

I've read the entire oracle documentation for java enum, I know how it works and all the basics but I have no clue about the body of the above enum class Are Player () , Enemy () constants ? functions ? Also what would this return ID.Player();

Upvotes: 3

Views: 70

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

Just as with regular classes, you get a default no-arg constructor with enums if you don't declare an explicit constructor.

The language spec says:

In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause.

Slightly before that, it also says:

An enum constant may be followed by arguments, which are passed to the constructor of the enum ... If the arguments are omitted, an empty argument list is assumed.

As such, these are just enum constants, explicitly invoking that implicit constructor. It's exactly the same as if you omitted the ().

Upvotes: 8

Related Questions