A New JEP to Enhance Java Enums [Code Snippet]
Enums a versatile and useful, but they currently don't support generics. One JEP has proposed fixing that, providing even greater use for enums.
Join the DZone community and get the full member experience.
Join For FreeEnum is one of the strongest features in Java. They are used as a list of constraints. An enum can contain a constructor, a method, a field etc. This link goes into some more details, but we're going to cover one important aspect of them here.
They don't support generics.
Let's check the following code:
public enum Cars {
AUDI(new Audi()),
ACURA(new Acura());
private Vehicle vehicle;
Cars(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Vehicle getVehicle() {
return vehicle;
}
}
public abstract class Vehicle {
}
public class Acura extends Vehicle {
public int getSerialNo() {
return 134;
}
}
public class Audi extends Vehicle{
public String getName() {
return "Audio";
}
}
We have two different methods in the two classes. Now we can access the enum using the following:
public class Main {
public static void main(String[] args) {
Vehicle vehicle = Cars.ACURA.getVehicle();
}
}
But there is no way we can call the getSerialNo() method from this.
To solve this problem, a new JEP (JDK Enhancement Proposal) has submitted.
With this JEP, we will able to do following:
public enum Cars<T extends Vehicle> {
AUDI<Audi>(new Audi()),
ACURA<Acura>(new Acura());
private T vehicle;
Cars(T vehicle) {
this.vehicle = vehicle;
}
public T getVehicle() {
return vehicle;
}
}
And, definitely, we will able to call the getSerialNo() method like following:
Cars.ACURA.getVehicle().getSerialNo();
Opinions expressed by DZone contributors are their own.
Comments