I have seen constructs with an enum declared inside an enum. What is this used for ?
Enums can be defined as members of a class aka 'nested enum types'. Nested enum defined as member of a class. //In file Employee.java. public class Employee { enum Department {
So the first thing that I thought was using an Enum to store all the naming there and easily access them. Unfortunately, it turned out that Enums are actually not that flexible. Meaning that you can't have nested or multi-level Enums.
They are type safe and comparing them is faster than comparing Strings.
With an enum it can get more complicated due to having separate values for name and toString, and those values possibly being used in conditional logic.
Enums in Java can't be extended, so if you wanna collate strongly-related enums in one place you can use these nested enum constructs. For example:
public enum DepartmentsAndFaculties
{
UN (null, "UN", "University"),
EF (UN, "EF", "Engineering Faculty"),
CS (EF, "CS", "Computer Science & Engineering"),
EE (EF, "EE", "Electrical Engineering");
private final DepartmentsAndFaculties parent;
private final String code, title;
DepartmentsAndFaculties(DepartmentsAndFaculties parent, String code, String title)
{
this.parent = parent;
this.code = code;
this.title = title;
}
public DepartmentsAndFaculties getParent()
{
return parent;
}
public String getCode()
{
return code;
}
public String getTitle()
{
return title;
}
}
Here, inner enums consist of {parent enum, code, title} combinations. Example usage:
DepartmentsAndFaculties cs = DepartmentsAndFaculties.CS;
cs.getTitle();
You can see the power of nested enums when constructing hierarchical entities/enums.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With