Java Enum implementing an Interface

In this tutorial you will learn how to implement an Interface with an Enum in Java.

Introduction

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. Environment: Ubuntu 12.04 JDK 1.7.0.09

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: Operator.java package com.byteslounge.enums; public interface Operator { int calculate(int firstOperand, int secondOperand); } Now we define a Enum that implements this interface. In this example we will only consider the sum and the subtraction operators. EOperator.java 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: Operation.java 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: Main.java 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: Sum: 15

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

Download source code from this article

Related Articles

Comments