Skip to content
Advertisement

Use of adding functions/fields to enum cases in Java other than overriding?

By accident I just discovered that the Java 1.8 compiler allows the following syntax:

JavaScript

Overriding toString() individually works perfectly fine. A call on an AnimalType.DOG results in the String “I am a dog”.

Apart from this though, I couldn’t find any information on what this enum case customization could be used for. Note the other public method for the case CAT. When defining any other public method or field, it seems like it can’t be accessed from the outside anyway.

So what’s the deal about this? Is this just something that is technically correct syntax but pointless?

Advertisement

Answer

toString is inherited from Object, but behavior is still polymorphic: DOG and CAT “print themselves” differently. Now your own custom methods (like, sound() in the following example) will make much more sense if you ‘ll use an abstract method at the level of AnimalType enum definition:

JavaScript

Now you can add polymorphic custom behavior to the enum and use it without known the actual animal:

JavaScript

The actual usages can vary, out of my head, you can implement finite state machine, parsing if enums are tokens, calculations if enums are geometric figures (like calculate volume of 3d figure) and what not. Its a tool for java programmers like many others. Use it wisely 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement