Strange behavior with Java enums -
i run strange behavior java enums. if write next enum:
public enum test {    public static final int c1 = 5; } you got compilation error, expected because did not declare enum constants in beginning.
but strange part if add semicolon without constant name in beginning:
public enum test {    ;    public static final int c1 = 5; } your code compiled successfully.
maybe question dumb , there answer in java specification have not found 1 yet.
if understands why java compiler so, please explain.
as answer pointed out, relevant section of jls 8.9, 8.9.1 states:
the body of enum declaration may contain enum constants. enum constant defines instance of enum type.
enumbody:
{ [enumconstantlist] [,] [enumbodydeclarations] }
to understand meaning of enumbody definition 1 must @ jls chapter 2.4, grammar notation, says
the syntax {x} on right-hand side of production denotes 0 or more occurrences of x.
also
the syntax [x] on right-hand side of production denotes 0 or 1 occurrences of x. is, x optional symbol. alternative contains optional symbol defines 2 alternatives: 1 omits optional symbol , 1 includes it.
how relate question? means valid enum declarations following (some grammar notation follows, bear me):
public enum test { }  public enum test {   [enumconstantlist] }  public enum test {   [enumconstantlist] , }  public enum test {  , }  public enum test {   [enumbodydeclarations] }  public enum test {  , [enumbodydeclarations] }  public enum test {   [enumconstantlist] [enumbodydeclarations] }  public enum test {   [enumconstantlist] , [enumbodydeclarations] } [enumconstantlist] not interesting because it's 1 expect:
enumconstant {, enumconstant}
that is, 1 or more enumconstant separated commas (i'm not going definition of enumconstant, i've fallen deep enough rabbit hole plus it's not relevant question).
things interesting (finally) definition of [enumbodydeclarations]:
enumbodydeclarations:
; {classbodydeclaration}
this why first example invalid
you incorrectly specified enumbodydeclarations above excerpt shows non-optional semicolon followed 0 or more classbodydeclaration. 
this why second example valid
it contains non-optional semicolon followed valid classbodydeclaration. 
phew.
this means following valid enum declarations:
public enum test {  ; }  public enum test {  ,; }  public enum test {    ,;    public static final int c1 = 5; }  public enum test {    cat, }  public enum test {    cat; }  public enum test {    cat,; }  public enum test {    cat,;    public static final int c1 = 5; }  public enum test {    cat;    public static final int c1 = 5; } but never
public enum test {    cat,    public static final int c1 = 5; } 
Comments
Post a Comment