13

So I have looked around google and SO , I cannot find a example or explanation of : What is the purpose of static final methods in enum?

What I understand :

  1. Methods declare static can be accessed like function/procedural languages.
  2. final means you can't override it. Can't change the reference. As assylias pointed out in comments static can't be overridden either.
  3. enums can't be subclassed, explained here.

So what's the point of static final methods in enums if it will never be overridden since there won't be a subclass?

Community
  • 1
  • 1
wtsang02
  • 18,603
  • 10
  • 49
  • 67

4 Answers4

19

By making a static method final, you prevent it from being hidden (only instance methods can be overriden) by a subclass.

Since enum can't be subclassed, making a static method final is superfluous but not forbidden.

Note: technically, each enum constant that has a class body implicitly defines an anonymous class that extends the enum. But since inner classes may not declare static methods, the static final method could not be hidden in such a constant's class body.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    +1 Actually there are cases where Enum can be subclassed, for example in `enum SomeEnum { VALUE1{}, VALUE2{}; }` VALUE1{} is anonymous class of `SomeEnum` type. But since we can't add static methods to non static inner classes (like anonymous classes) using `final` with `static` here is overkill. – Pshemo Jan 10 '13 at 19:25
  • @Pshemo That's a good point - I have edited my answer and added references. – assylias Jan 10 '13 at 19:33
4

It's easy to see why static methods make sense, so I guess the question is about the final modifier.

final serves no purpose here, except maybe make the code a bit easier to read, but not by much.

It's similar to the way interface methods are often written as public void foo();, even though interface members are always public anyway.

biziclop
  • 48,926
  • 12
  • 77
  • 104
2

In Java Enum types are used to represent fixed set of constants and making it static final helps its initialisation only once, single copy to be shared across all instances, accessing the variable with the class name and with final its more like a read-only

Santosh Sindham
  • 879
  • 8
  • 18
0

When you declare instances of an enum you can override the enum's methods, essentially enum instances are implemented as (or thought of) as subclasses. static methods can't be overridden in any case but the implication in the OP and other answers that final is superfluous for an enum is false.

djechlin
  • 59,258
  • 35
  • 162
  • 290