Implement an Interface using an Enum in Java
Hello everyone, in this post, we will learn how to implement an interface using an Enum in Java. As we know, Enums are used to represent a group of named constants. For example, we can represent all the days of a week using an enumerated type named week. An enum type has a fixed set of values. It can take one of the values from this set at a time. In Java, Enums are static and final and are defined by using ‘enum’ keyword. In this tutorial, we will see how we can implement an interface in Java using an Enum.
Enums are a special kind of class in Java and like any other class, they can contain constants and methods where the defined constants are the only possible instances for this class. This class extends the abstract class java.lang.Enum implicitly. Hence an Enum cannot extend some other class or enum and it cannot be extended either. But we can implement an interface in Java using enums where we need to implement some business logic that is tightly coupled with a discriminatory property of a given class or object.
Have a look at the below Java program to understand the above.
interface pet{ public String name_of_the_pet(); } enum Pets implements pet{ Dog, Cat, Rabbit; public String name_of_the_pet() { if(ordinal() == 0) return "Dog"; if(ordinal() == 1) return "Cat"; else return "Rabbit"; } } public class Example{ public static void main(String args[]) { Pets p = Pets.Cat; System.out.println("Name of the pet is: " + p.name_of_the_pet()); } }
Save the above program as Example.java and run it.
Output:
Name of the pet is: Cat
As you can see, in the above example program we have an interface named pet which is implemented using enum type Pets. The enum type Pets can take any value from Dog, Cat, and Rabbit. The ordinal() method in the program is defined in java.lang.Enum and it returns the ordinal of this enumeration constant.
You may also read: Conversion of String to Enum in Java
Leave a Reply