Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

like image 454
Laith Zeyad Avatar asked Apr 18 '26 13:04

Laith Zeyad


1 Answers

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

like image 191
Andy Turner Avatar answered Apr 20 '26 04:04

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!