java - Enum constructor takes in more parameters than specified -
i have following code , try understand does
public enum exampleclass { instance("nothing"), item; private string description; private exampleclass(string description) { this.description = description; } static{ item = new exampleclass("item", 1, "this item"); } }
my questions are:
- what instance("nothing") ?
- the exampleclass takes in 1 variable in constructor, why inside static block item takes in 3?
exampleclass
enum
. instance
, item
2 instances of exampleclass
(called enum constants). example, valid :
public enum exampleclass { instance, item; }
that said, can define own constructors enum, 1 :
private exampleclass(string description) { this.description = description; }
in same way classes, if define custom constructor, jvm not create default constructor.
instance("nothing")
instantiated using custom constructor.item
not valid because there no 'no-arg' constructor.
this valid:
public enum exampleclass { instance("nothing"), item; private string description; //will used instantiate instance("nothing") private exampleclass(string description) { this.description = description; } //will used instantiate item private exampleclass() { } }
new exampleclass("item", 1, "this item");
worse : cannot instantiate enum new
. 1 instance of every enum literal can exist , handled jvm itself.and if possible, there no constructor 3 args still not compile
Comments
Post a Comment