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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button