Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a Java enum be final?

Tags:

java

enums

final

public interface Proposal  {       public static final enum STATUS {          NEW ,         START ,         CONTINUE ,         SENTTOCLIENT     };  } 

Java does not allow an enum to be final inside an interface, but by default every data member inside an interface is public static final. Can anybody clarify this?

like image 744
Zuned Ahmed Avatar asked Mar 27 '12 14:03

Zuned Ahmed


People also ask

Should enum fields be final?

The members of the enum are constants, but the reference variable referring to enum values is just like any other reference variable, hence the need to mark them as final .

Are enum values final?

An enum type is implicitly final unless it contains at least one enum constant that has a class body. It is a compile-time error to explicitly declare an enum type to be final. Nested enum types are implicitly static.

Are enums static and final?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Does enum have to be all caps?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.


1 Answers

Java does not allow you to create a class that extends an enum type. Therefore, enums themselves are always final, so using the final keyword is superfluous.

Of course, in a sense, enums are not final because you can define an anonymous subclass for each field inside of the enum descriptor. But it wouldn't make much sense to use the final keyword to prevent those types of descriptions, because people would have to create these subclasses within the same .java file, and anybody with rights to do that could just as easily remove the final keyword. There's no risk of someone extending your enum in some other package.

like image 125
StriplingWarrior Avatar answered Sep 19 '22 01:09

StriplingWarrior