I am reading a book on programming and I met such thing:
public static enum Month {
JANUARY(1),
FEBRUARY(2),
MARCH(3),
APRIL(4),
MAY(5),
JUNE(6),
JULY(7),
AUGUST(8),
SEPTEMBER(9),
OCTOBER(10),
NOVEMBER(11),
DECEMBER(12);
Month(int index) {
this.index = index;
}
What does a number in parentheses mean after an enum instance? Is it an enum constructor?
What does a number in parentheses mean after an enum instance? Is it an enum constructor?
JANUARY(1), FEBRUARY(2), etc... are indeed enum constructors.
But a number is not necessary required to specify a constructor in an enum. Here you have a number but it could be anything else and it could also have as many arguments as required.
Note that actually the enum declaration misses the index field and could not compile.
It would be correct :
public static enum Month {
JANUARY(1),
FEBRUARY(2),
MARCH(3),
APRIL(4),
MAY(5),
JUNE(6),
JULY(7),
AUGUST(8),
SEPTEMBER(9),
OCTOBER(10),
NOVEMBER(11),
DECEMBER(12);
private int index;
Month(int index) {
this.index = index;
}
}
I would add that an enum is above all a class. So each enum values (here JANUARY, FEBRUARY, ...) will be instantiated by invoking the class constructor.
And as for any class, as you don't define a constructor the compiler will generate a default with no arg.
So it is valid :
public static enum Fruit {
APPLE(),
ORANGE();
Fruit() {
}
}
That is also valid :
public static enum Fruit {
APPLE(),
ORANGE();
}
But for enums with no arg in the constructor, we generally use this convenient syntax reserved for enums :
public static enum Fruit {
APPLE, // with no parenthesis
ORANGE; // with no parenthesis
}
This is the constructor being invoked by every enum value:
Month(int index) {
this.index = index;
}