Nested enum Java
Enum types must be defined first. The different ways that enums can be defined, including as members of other classes, in their own class files, or next to other class definitions. The advantages of utilising enums are then briefly discussed, along with enum equality. The principles of Java enums are initially covered, and then expanded enums containing variables, methods, and constructors are explained along with extensive code examples. The concept of overriding a specific method for an enum constant, also known as a constant specific class body. Enums can be effectively utilised with switch-case statements to select between various execution routes. Enums are types that stand in for a predetermined group of connected constants. The terms used to simplify the aforementioned definition are:
- Defined Set: Enums have a fixed number of values that are specified up front when defining an enum type.
- Related Constants: The defined fixed set of values for a specific enum type. As a result, these enum values share a similar enum type.
- Enums are kinds: Enums are special types of classes, making them types in and of themselves.
Enums examples
- Organizational departments include marketing, operations, information technology, and human resources. As a result, the department names make up the fixed set of enum values for a Department enum.
- SMALL, MEDIUM, LARGE, and EXTRA LARGE are all shirt sizes that are available. As a result, the different shirt sizes make up the fixed set of enum values for the ShirtSize enum.
Setting Up an Enum
Expanding on the Category enum from the first sample example. Start by creating the following code to define a fixed set of constant values for various categories as an enum.
Simplest enum definition
public enum Category {
Human Resource, IT, Finance, Digital Marketing
}
Important details in the enum definition above:
- Four values make up the category enum: Human Resource, IT, Finance, and Digital Marketing.We can use category to retrieve the 4 category constants.IT, Human Resources, and so forth.
- The semi-colon (;) at the end of enum constants is unnecessary unless you want to add more to the enum in terms of variables, methods, etc., which will be covered later under the topic enhanced enums.
- It's important to keep in mind that at this stage.
Enums are unique kinds of classes.
Every enum type is a class. The compilers inserts a lot more boilerplate code while compiling an enum type, which is what gives all enum type class their "special" quality. This boilerplate code offers attributes of a complete class and definitions for object constants based solely on the enum declaration. Therefore, the compiler effectively creates a type as well as its constant objects behind the scenes and abstracts it out as a straightforward declaration of an enum type and constants. As a result, all a developer needs to do is specify an enum type and its constants; the compiler will take care of the rest for them.
Now review all the features that an enum type can access to the Java compiler:
- Implicitly, every enum extends Java.lang.Enum.
- All enums have access to the Enum-inherited methods name(), ordinal(), and function valueOf() .
- The only explicit way to generate an enum object is through reflection.
- Boilerplate code includes the declaration of a predetermined set of instance variables that are public static final objects that correspond to each of the enum constants offered for that type.
- On all enum types, the static values() function is provided. The values() method, when used on an enum type, produces an array containing every enum constant created for that enum type.
- The compiler automatically overrides the toString()method for all enum constants, returning the name of the enum constant instead.
Enum Naming Standard
Enum values are traditionally named using capital letters and underscores ( ). Enum values are constant values, and in Java, the first character of a constant name must be a capital letter, followed by an underscore.
Where are enums defined:
Enums can be defined in the same ways as other Java type definitions, including: Enums may be individually defined (as a top-level class) in a file containing nothing else but the enum definition.
//category.java
public enum Category{
Human Resource, IT, Finance, Digital Marketing
}
// EnumTest.java
public class EnumTest {
public static void main(String args[]) {
Category enumV = Category.Human Resource;
}
}
Clearly define what an enum is!
A set of fixed/constant instances of an enum 'type' constitutes an enum logically speaking. Human Resource, IT, Finance, and Digital Marketing are the four consistent instances of the Category type mentioned above. Now, only one of these four constant values may be assigned to any variable specified in any class that is of type Category.
Advantages to using enums
Enums limit the values to the specified constants, which is very advantageous for system designers. In a system with 4 departments, only these 4 values may be assigned to any Category type variables used anywhere in the system. This reduces the number of potential flaws and enhances the maintainability of the code.
Introducing upgraded enums in addition to the standard enum
It is now time to examine an enum's full potential as a "type" after seeing how to construct a basic enum and utilise it in code. Enums are simply classes, albeit ones of a "special" sort, as we saw above. An enum type can therefore define methods, variables, and constructors because it is a class. Additionally, method definitions for particular enum constants can be selectively overridden. To examine these advanced enum features right away. At first imagine that for each category enum constant, we need to create a "Category Code." It will store this code as a String because it will be alphanumeric. It may define a getter function and a private instance variable for the Category enum's department code, just like we would in a class definition. As we design the enum itself, it ill also define a function Object() for passing the category code. One thing to keep in mind concerning enum constructors is that they are all implicitly private, including the Category enum function Object(). Therefore, the compiler implicitly thinks that an enum function Object()is private even if there is no access modifier set for it. A compiler error would occur if an enum function Object was defined with public or protected access.
Enum that selectively overrides instance methods
Now expand the department use case a little in order to better comprehend this enum feature. The Human Resource category had a concern about its code being exposed to everyone after seeing the display seen above, where all department codes are publicly accessible. It has requested that only its department code be protected from any attempts by the public to access it, such as through the values() method call, and that the string "NOT ACCESSIBLE" be returned in place of the actual deptCode value. Due to this need, we must modify the getDeptCode() method's behaviour such that it only affects the enum constant HR. Fortunately, enum does allow for selective method override for particular constants.
Switch-case and enumerations
Enums are frequently utilised to choose between various execution pathways when employing switch-case statements. It is convenient to use that enum type in switch statements and provide the logic to execute for each of the enum constants of that type using the appropriate case when the choice of which execution path to choose can be reduced to a single enum constant value.The procedure in the code sample that is displayed next prints various outputs for each of the four department types depending on which Department enum constant is supplied as input to the switch statement. The values() function is used by the EnumTest class to run through the Department enum constants, ensuring that each enum constant is encountered exactly once.
public class EnumTest {
public static void main(String args[]) {
for (Category cat : Category.values()) {
switch (cat) {
case Human Resource:
System.out.println("Case – Human Resource");
break;
case IT:
System.out.println("Case - IT");
break;
case Finance:
System.out.println("Case - Finance");
break;
case Digital Marketing:
System.out.println("Case – Digital Marketing");
break;
}
}
}
}
Output:
Case – Human Resource
Case – IT
Case – Finance
Case – Digital Marketing
Enums were fully comprehended in the aforementioned tutorial. Starting with the fundamentals, we examined what enums are, how to define them, the naming convention for enum constants, where to define them, how to use their static values() and function valueOf()methods, enum equality, and ordinal values. Then, we looked at extended enums with class-specific constructors, constructor-specific constants, and variables. Finally, we looked at how switch-case statements may be used to express conditional logic using enums.