Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static final methods in enum

Tags:

java

oop

enums

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?

like image 715
wtsang02 Avatar asked Jan 10 '13 18:01

wtsang02


2 Answers

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.

like image 58
assylias Avatar answered Oct 06 '22 08:10

assylias


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.

like image 29
biziclop Avatar answered Oct 06 '22 09:10

biziclop