
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can Enum Implement 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
Advertisements