Java public interface enum

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.

      Источник

      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:

      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:

      Источник

      Can Enum implements an interface in Java?

      Yes, Enum implements an interface in Java, it 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. An Enum is a special datatype which is added in Java 1.5 version. The Enums are constants, by default they are static and final so the names of an enum type fields are in uppercase letters.

      Example

      interface EnumInterface < int calculate(int first, int second); >enum EnumClassOperator implements EnumInterface < // An Enum implements an interface ADD < @Override public int calculate(int first, int second) < return first + second; >>, SUBTRACT < @Override public int calculate(int first, int second) < return first - second; >>; > class Operation < private int first, second; private EnumClassOperator operator; public Operation(int first, int second, EnumClassOperator operator) < this.first = first; this.second = second; this.operator = operator; >public int calculate() < return operator.calculate(first, second); >> // Main Class public class EnumTest < public static void main (String [] args) < Operation add = new Operation(20, 10, EnumClassOperator.ADD); Operation subtract = new Operation(20, 10, EnumClassOperator.SUBTRACT); System.out.println("Addition: " + add.calculate()); System.out.println("Subtraction: " + subtract.calculate()); > >

      Output

      Addition: 30 Subtraction: 10

      Источник

      Читайте также:  Factory method to create object in java
Оцените статью