Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

if enum is a constant why can't it be marked final?  RSS feed

 
S Fox
Greenhorn
Posts: 18
1
Eclipse IDE Firefox Browser Netscape
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was sure that enums are constant, but since it doesn't allow the final keyword i became very confused and had to look it up. oracle says on a webpage they are constant... but why can't it be final?
oracle

This question page on stack overflow makes it worse, nobody can agree why. Someone there says it's implicitly static and final therefore you cant write final. If that is true, then why are we able to write static on it but not final?
stack overflow
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66203
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would it make sense to make it non-final? If not, and it's implicitly final, why bother allowing the keyword?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question on Stack Overflow is complicated beacuse people are mixing up different things, not just asking about an enum, but an enum nested in an interface. The poster says that "by default every data member inside an interface is public static final", which leads to unnecessary confusion in the answers.

A type nested within an interface is not, in general, implicitly final. For example, a class or interface nested in an interface is not implicitly final. It's true that fields (data) in an interface are implicitly final, as well as public and static. But that does not mean that a nested type is final.

The constants inside an enum are implicitly final, sure. But that's not the same as the enum itself being final.

So, is an enum actually implicitly final, or not? The precise rule is given in the JLS:
An enum declaration is implicitly final unless it contains at least one enum constant that has a class body

That's because, when an enum constant has a class body, the compiler will need to make a subclass of the enum class in order to hold whatever implementation details are defined in the body.

In general, you don't need to know or care. The compiler will make the enum final if it can, and you shouldn't try to interfere by doing so yourself.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!