Why can't a Java enum be final?

2019-02-04 05:36发布

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?

标签: java enums final
4条回答
闹够了就滚
2楼-- · 2019-02-04 06:00

No point in declaring enum final. Final for classes means that they can not be inherited. However, enums can not be inherited by default (that is they are final).

The final thing is valid only for variables. However you should think of the enums more like data types than variables.

查看更多
聊天终结者
3楼-- · 2019-02-04 06:12

Two things:

  1. enums are final subclasses of java.lang.Enum
  2. if an enum is a member of a class, it is implicitly static
查看更多
贪生不怕死
4楼-- · 2019-02-04 06:19

An enum can't be final, because the compiler will generate subclasses for each enum entry that the programmer has explicitly defined an implementation for.

Moreover, an enum where no instances have their own class body is implicitly final, by JLS section 8.9.

查看更多
小情绪 Triste *
5楼-- · 2019-02-04 06:19

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.

查看更多
登录 后发表回答