Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested enum-why is it used?

Tags:

java

enums

I have seen constructs with an enum declared inside an enum. What is this used for ?

like image 887
mafalda Avatar asked Jan 17 '11 23:01

mafalda


People also ask

What is nested enum in Java?

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 {

Can enums be nested?

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.

Why enums are better than strings?

They are type safe and comparing them is faster than comparing Strings.

Why we should not use enum in Java?

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.


1 Answers

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.

like image 57
Juvanis Avatar answered Oct 28 '22 12:10

Juvanis