Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using integer in enumerated type

Tags:

java

enums

I am trying to declare this enum:

public enum Month {
    1, 2, 3, 4, 5 , 6, 7, 8, 9, 10, 11, 12;
}

But when I try to compile it doesn't work. Is this because the constants are integers?

like image 825
James Avatar asked Jan 19 '23 01:01

James


1 Answers

Yes - the values of an enum have to be valid identifiers. They're basically static fields after all - you're effectively trying to declare:

public static Month 1 = new Month();

which obviously isn't valid.

See the Java Language Specification section 8.9 for details, but in particular this production:

EnumConstant:
Annotations Identifier Argumentsopt ClassBodyopt

like image 175
Jon Skeet Avatar answered Jan 31 '23 01:01

Jon Skeet