#
Enum implements an Interface (II)
This tutorial explains to you how we can implement an interface in an Enum in Java.
Enums are used to represent a group of named constants. An enum type has a fixed set of values.
In Java, Enums are static
and final
and are defined by using "enum" keyword.
In this case, could an enum type implement an interfaces ?
YES, it is possible. If an enum type implements an interface, it must also provide implementation for all abstract methods from the interface.
Additional things regarding an enum type:
- An enum type is never inherited by another enum type.
- You cannot declare an enum type as abstract.
The enum type will still be an enum type, however when implements an interface, this enum will also have a method defined for each value in the enum. That method could be defined at the enum type level (see Enum implements an Interface (I)). or for each value (see below).
In the example below we will define a list of fixed values (using an enum type) which keeps an implementation of the execute()
method.
This pattern is useful when we have a method which is called only using a limited number of predefined parameters.
My example is using Spring Boot, and it is created by using Spring Initializr.
Here are the code I created/updated:
- The interface:
package com.example.operation;
public interface IMyOperation {
public void execute();
}
- The enum type:
package com.example.operation;
public enum MyOperation implements IMyOperation {
PAINT {
@Override
public void execute() {
System.out.println("We are PAINTING a car.");
}
},
FIND {
@Override
public void execute() {
System.out.println("We are FINDING a car.");
}
};
}
- The usage:
package com.example;
import com.example.operation.MyOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringApplication {
public static void main(String[] args) {
org.springframework.boot.SpringApplication.run(SpringApplication.class, args);
System.out.println("Here starts the Spring application !");
MyOperation.PAINT.execute();
MyOperation.FIND.execute();
}
}
When we run the application we can see on the console:
Here starts the Spring application !
We are PAINTING a car.
We are FINDING a car.
Process finished with exit code 0
Personally, I prefer Enum implements an Interface (I), but that depends also on the particular situation we face.