Java enum and interface

Java : Extensible Enum with Interface

In Java Enum is a powerful data type. Many places user uses Enum To get advantages from Enum type. Like In a Static Factory method it wise decision to pass Enum type rather than pass String. Below , I mention some situations where using Enum is advantageous.

Enum Advantages

    1. In a Static Factory method passing Enum type as argument make the method typesafe. Method users can’t pass an arbitrary value to this method.
    2. Instead of using bit fields using Enum and EnumSet make the code cleaner and easy to maintain.
    3. Using Enum one can achieve Singleton pattern which is inherently Thread Safe.
    4. Using Strategy Enum Pattern one can get rid of If/Switch statements.

Enum DisAdvantage

“Can we Extend Enum and When it is needed?”

Yes we can emulate the extensibility in Enum but we have to play in a strategic way ,
We know that Enum can’t be extended but we know the fact that an Interface can be extended and Enum can implement the Interface. So combining these two statements we can achieve extensibility. Where Enum can’t be extended but an interface can so If we use “Coding to an Interface” Strategy we can easily replace BaseType enum with Our Extended Enum.
Now coming to the use case,
According to Joshua Bloch ,“There is at least one compelling use case for extensible enumerated types, which is operation codes, also known as opcodes. An opcode is an enumerated type whose elements represent operations on some machine, such as the Operation”
Sometimes it is desirable to let the users of an API provide their own operations,effectively extending the set of operations provided by the API.”

According to Josh Bloch In a case of operation, we can provide some basic operation in an Enum like a simple calculator and basic operations are plus ,minus etc but if API Users want more like XOR , Square root, they can achieve it through extending Operation Interface and create a new Enum.

Steps For Achieving Extensibility

Let’s take a Use Case , We have an Enum call Direction in an API ,it has entries for NORTH,SOUTH,EAST,WEST but most of the cases API Users use these basic directions but when it is about to showing the shortest path between source and destination API Users need some advanced direction like NORTH-EAST,NORTH-WEST etc.

How judiciously we implement the API so Users can have the option to extend the Basic Direction Enum?

    1.Create an Interface called Direction and declares a method called showDirection().
    2. Create a BasicDirection enum by implement Direction interface.
    3. Put entries for NORTH,SOUTH,EAST,WEST.
    4. Please note that as it implements Direction interface , each Enum has to override showDirection method.
    5. Create an AdVANCEDIRECTION enum with NORTH-EAST,NORTH-WEST etc entries.
    6. Use this Enum anywhere.
Читайте также:  Какие nokia поддерживают java

public interface Direction

public void showDirection();

public enum BasicDirection implements Direction

@Override
public void showDirection() System.out.println(«I am NORTH»);

@Override
public void showDirection() System.out.println(«I am South»);

@Override
public void showDirection() System.out.println(«I am EAST»);

@Override
public void showDirection() System.out.println(«I am WEST»);

public enum AdvanceDirection implements Direction NORTHEAST

@Override
public void showDirection() System.out.println(«I am NORTH-EAST»);

@Override
public void showDirection() System.out.println(«I am NORTH-WEST»);

@Override
public void showDirection() System.out.println(«I am SOUTH-EAST»);

@Override
public void showDirection() System.out.println(«I am SOUTH-WEST»);

public class DirectionDriver

public static void printDirection(Direction op)
op.showDirection();
>

public static void main(String[] args)

I am EAST
I am SOUTH-WEST
I am NORTH
I am South
I am EAST
I am WEST
I am NORTH-EAST
I am NORTH-WEST
I am SOUTH-EAST
I am SOUTH-WEST

    printDirection which takes Direction as Input and I pass an Enum to it.
    Another version is printDirections method it prints all Enum entries to achieve that

Источник

How to implement an Interface using an Enum in Java

Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. We have already discussed the basics of enum, how its declared in the previous article. In this article, we will understand how an enum implements an interface.

We primarily use enums when a method parameter can only take the value out of a small set of possible values means the input values are fixed and it takes from that fixed set of values. Java enum type is a special kind of java class which can contain constants and methods like normal java classes where the values are the only possible instances of this class. This enum extends the abstract class java.lang.Enum. Consider a situation when we have to implement some business logic which is tightly coupled with a discriminatory property of a given object or class at that time we implement an interface with enum. Think about a case where we need to merge the values of two enums into one group and treat them similarly, there Enum implements the interface.

Since an enum is implicitly extending the abstract class java.lang.Enum, it can not extend any other class or enum and also any class can not extend enum. So it’s clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface. Therefore, in order to achieve extensibility, the following steps are followed:

The following is the code which demonstrates the implementation of an interface in an enum:

Источник

Java Enum implementing an Interface

Some developers are not aware of this fact but we can implement Interfaces with Enums in Java. This may 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 this tutorial we will see how to do it and also go through an example use case.

The Enum

In this example we will implement a mathematical operation. The type of the operation (or the operator) will be defined as an Enum. Following next is the operator interface:

Читайте также:  Index 0 size 0 error in java

package com.byteslounge.enums; public interface Operator

Now we define a Enum that implements this interface. In this example we will only consider the sum and the subtraction operators.

package com.byteslounge.enums; public enum EOperator implements Operator < SUM < @Override public int calculate(int firstOperand, int secondOperand) < return firstOperand + secondOperand; >>, SUBTRACT < @Override public int calculate(int firstOperand, int secondOperand) < return firstOperand - secondOperand; >>; >

The operation class

Now let’s define the Operation class:

package com.byteslounge.enums; public class Operation < private int firstOperand; private int secondOperand; private EOperator operator; public Operation(int firstOperand, int secondOperand, EOperator operator) < this.firstOperand = firstOperand; this.secondOperand = secondOperand; this.operator = operator; >public int calculate() < return operator.calculate(firstOperand, secondOperand); >>

The firstOperand and secondOperand properties represent the members of the operation. The result of the operation will depend on the operator Enum type property. For the result calculation we will invoke calculate method that is implemented by the Enum itself (operator.calculate(firstOperand, secondOperand)).

Testing

Let’s define a simple class to test our example:

package com.byteslounge.enums; public class Main < public static void main (String [] args)< Operation sum = new Operation(10, 5, EOperator.SUM); Operation subtraction = new Operation(10, 5, EOperator.SUBTRACT); System.out.println("Sum: " + sum.calculate()); System.out.println("Subtraction: " + subtraction.calculate()); >>

When we run this test the following output will be generated:

This example source code is available for download at the end of this page.

Download source code from this article

Comments

Gonçalo Marques is a Software Engineer with several years of experience in software development and architecture definition. During this period his main focus was delivering software solutions in banking, telecommunications and governmental areas. He created the Bytes Lounge website with one ultimate goal: share his knowledge with the software development community. His main area of expertise is Java and open source.

He is also the author of the WiFi File Browser Android application:

Источник

Extensible Enum With Interface

Join the DZone community and get the full member experience.

In Java, Enum is a powerful data type. There are a lot of places you can use Enum to take advantage of it, like in a Static Factory method. There, it’s a wise decision to pass the Enum type rather than passing a String. Below, I mention some situations where using Enum is advantageous.

Enum Advantages

    1. In a Static Factory method, passing Enum as an argument makes the method typesafe. Method users can’t pass an arbitrary value to this method.
    2. Instead of using bit fields, using Enum and EnumSet makes the code cleaner and easy to maintain.
    3. Using Enum can achieve a Singleton pattern, which is inherently Thread Safe.
    4. You can also use them to get rid of If/Switch statements.

    Although Enum has several advantages, it has one major disadvantage. We cannot extend Enum.

    So the Question is, “Can we extend Enum, and ehen it is needed?”

    Yes we can emulate the extensibility in Enum, but we have to do it in a strategic way.

    We know that Enum can’t be extended, but we know the fact that an Interface can be implemented and Enum can implement the Interface. So, combining these two statements, we can achieve extensibility. Where Enum can’t be extended, if we use the “Coding to an Interface” Strategy, we can easily replace BaseType Enum with our Extended Enum.

    Now coming to the use case:

    According to Joshua Bloch, “There is at least one compelling use case for extensible enumerated types, which is operation codes, also known as opcodes. An opcode is an enumerated type whose elements represent operations on some machine, such as the Operation. Sometimes, it is desirable to let the users of an API provide their own operations, effectively extending the set of operations provided by the API.”

    According to Josh Bloch, in the case of an operation, we can provide some basic operations in an Enum — like plus/minus in a simple calculator — but if API users want more, like a square root operation, they can achieve it through extending the Operation Interface and create a new Enum.

    Steps For Achieving Extensibility

    Let’s take a use case where we have an Enum called Direction in an API. It has entries for NORTH, SOUTH, EAST, and WEST. In most cases, API users use these basic directions, but when it is about to show the shortest path between the source and the destination, API users need some advanced direction, like NORTH-EAST, NORTH-WEST, etc.

    How can we judiciously implement the API so users can have the option to extend the Basic Direction Enum?

    Steps

      1. Create an Interface called Direction and declare a method called showDirection().
      2. Create a BasicDirection Enum by implementing Direction.
      3. Put entries for NORTH, SOUTH, EAST, and WEST.
      4. Please note that as it implements the Direction interface, each Enum has to override the showDirection method.
      5. Create an AdvanceDirection Enum with NORTH-EAST, NORTH-WEST, etc. entries.
      6. Use this Custom Enum/Basic Enum anywhere interchangeably.

      Java Code

      Direction Interface

      package com.example.enumtest; public interface Direction

      BasicDirection Enum

      package com.example.enumtest; public enum BasicDirection implements Direction < NORTH < @Override public void showDirection() < System.out.println("I am NORTH"); >>, SOUTH < @Override public void showDirection() < System.out.println("I am South"); >>, EAST < @Override public void showDirection() < System.out.println("I am EAST"); >>, WEST < @Override public void showDirection() < System.out.println("I am WEST"); >> > 

      AdvanceDirection Enum

      package com.example.enumtest; public enum AdvanceDirection implements Direction < NORTHEAST < @Override public void showDirection() < System.out.println("I am NORTH-EAST"); >>, NORTHWEST < @Override public void showDirection() < System.out.println("I am NORTH-WEST"); >>, SOUTHEAST < @Override public void showDirection() < System.out.println("I am SOUTH-EAST"); >>, SOUTHWEST < @Override public void showDirection() < System.out.println("I am SOUTH-WEST"); >> > 

      DirectionDriver Class

      package com.example.enumtest; public class DirectionDriver < public static void printDirection(Direction op) < op.showDirection(); >public static & Direction> void printDirections(Class clazz) < for(Direction direction : clazz.getEnumConstants()) < direction.showDirection(); >> public static void main(String[] args) < DirectionDriver.printDirection(BasicDirection.EAST); DirectionDriver.printDirection(AdvanceDirection.SOUTHWEST); DirectionDriver.printDirections(BasicDirection.class); DirectionDriver.printDirections(AdvanceDirection.class); >> 

      Output

      I am EAST I am SOUTH-WEST I am NORTH I am South I am EAST I am WEST I am NORTH-EAST I am NORTH-WEST I am SOUTH-EAST I am SOUTH-WEST 

      Please pay attention to the class DirectionDriver, where I create two methods

      • printDirection , which takes Direction as the input, and I pass an Enum entry to it.
      • Another version is that the printDirection method prints all Enum entries. To achieve that, I make a generic type that says T must be an Enum and a subtype of Direction by& Direction>, then pass the class instance so I can iterate over EnumConstants.

      Published at DZone with permission of Shamik Mitra , DZone MVB . See the original article here.

      Opinions expressed by DZone contributors are their own.

      Источник

Оцените статью