Enum
Enum to implement an interface
With this example we are going to demonstrate how to use an enum to implement an interface. Implementing an interface with an enum can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. In short, to implement an interface
with an enum
you should:
- Create an interface.
- Create an enum that implements the interface and its method.
Let’s take a look at the code snippet that follows:
interface Named { public String name(); public int order(); } enum Planets implements Named { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune; // name() is implemented automagically. public int order() { return ordinal()+1; } }
Related Article:
Reference: Java Secret: Using an enum to build a State machine from our JCG partner Peter Lawrey at the Vanilla Java
This was an example of how to use an enum
to implement an interface
in Java.