How to write multiple Enums in a Class ?

An enum definition in Java is a like a class. The language provides the syntactic features that are particular to enums, but as far as the JVM is concerned, the enum is a class.

In fact, an enum that is declared:

public enum MyConstants{ ... }

is implemented at the JVM as:

public static class Enum { ... }

The rules for declaring enum classes is thus the same as for declaring classes. A .java file may have only one public class. You can therefore declare only one public enum in a .java file. You may declare any number of package-private enums. If you have multiple, closely related enums, there is no harm in declaring them all as nested members of an enclosing class:

public class MyEnumContainer {

    static enum MyEnum1 { ... }

    static enum MyEnum2 { ... }
    :
    :
}

In this case, you would need to import your MyEnumContainer, or refer to the constants as MyEnumContainer.MyEnum1.ENUM_ONE, for example. Note that all enums are static classes, so using the static keyword doesn't penalize you, but it isn't necessary.

Each of the member enum definitions must stand alone (i.e., it must be a complete enum definition). If you have constant-associated data, then each enum definition will need its own instance fields and constructor. If you have constant-specific methods, each enum will need to provide the methods. If you are concerned about a lot of code duplication, you can put the common code into a private static helper class, and then forward method calls to those within your enum definitions. Using your enum definitions, the nested enums should look something like  the following :

public final class Test{

    public enum Unit {
         HORIZONTAL ("HORIZONTAL"),
         VERTICAL   ("VERTICAL"),
         :
         :
         DIAGONAL   ("DIAGONAL");

         private final String e_name;

         Unit(String name)
             { this.e_name = name; }

         public String getName() { return e_name; }
    }

    public enum Code {
    :
    :
    }

    public enum Version{
    :
    :
    }
}

Source → Click Here

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself