JavaRush /Java Blog /Random EN /Enumerations in Java (java enum)
articles
Level 15

Enumerations in Java (java enum)

Published in the Random EN group
When programming, we often encounter the need to limit the set of valid values ​​for a certain data type. So, for example, the day of the week can have 7 different values, the month of the year can have 12, and the season can have 4. To solve such problems, many statically typed programming languages ​​provide a special data type - enumeration ( enum). Enumeration did not appear in Java right away. A specialized language construct enumwas introduced starting with version 1.5. Up to this point, programmers have used other methods to implement enumerations. Enumerations in Java (java enum) - 1

enum construct

Let's start with an example. enumLet's describe the data type for storing the time of year using :
enum Season { WINTER, SPRING, SUMMER, AUTUMN }
Well, a simple example of its use:
Season season = Season.SPRING;
if (season == Season.SPRING) season = Season.SUMMER;
System.out.println(season);
As a result of which SUMMER will be printed to the console . I think that the example is obvious and does not need explanation.

Enum is a class

By declaring enum, we implicitly create a class derived from java.lang.Enum. Conventionally, the construction enum Season { ... }is equivalent to class Season extends java.lang.Enum { ... }. And although the compiler does not allow us to explicitly inherit from java.lang.Enumus, it is still easy to verify that enumit is inherited using reflection:
System.out.println(Season.class.getSuperclass());
The following will be displayed on the console:
class java.lang.Enum
The actual inheritance is automatically performed for us by the Java compiler. Next, let's agree to call the class created by the compiler to implement the enumeration the enum-class, and the possible values ​​of the enumerated type as enum-a elements.

Enum members are instances enumof a -class that are statically accessible

Elements enum Season (WINTER, SPRING и т.д.)are statically accessible instances enumof the -class Season. Their static availability allows us to perform comparisons using the reference comparison operator ==. Example:
Season season = Season.SUMMER;
if (season == Season.AUTUMN) season = Season.WINTER;

Name and serial number of the enum element

As mentioned earlier, any enum-class inherits java.lang.Enum, which contains a number of methods useful for all enumerations. Example:
Season season = Season.WINTER;
System.out.println("season.name()=" + season.name() + " season.toString()=" + season.toString() + " season.ordinal()=" + season.ordinal());
The output will be:
season.name()=WINTER season.toString()=WINTER season.ordinal()=0
The methods name(), toString()and are shown here ordinal(). The semantics of the methods is obvious. It should be noted that these methods enumare inherited from the class java.lang.Enum. Getting an element enumby the string representation of its name Quite often the task arises of getting an element enumby its string representation. For these purposes, in each enum-class, the compiler automatically creates a special static method: public static EnumClass valueOf(String name), which returns an enumeration element EnumClasswith a name equal to name. Usage example:
String name = "WINTER";
Season season = Season.valueOf(name);
As a result of executing the code, the season variable will be equal to Season.WINTER. Please note that if the element is not found, an IllegalArgumentException will be thrown , and if it is nameequal null, a NullPointerException will be thrown . By the way, this is often forgotten. For some reason, many are firmly convinced that if a function takes one argument and under certain conditions throws an IllegalArgumentException , then when passing it there , an IllegalArgumentExceptionnull will certainly be thrown as well . But that's beside the point. Let's continue. Getting all the elements of an enumeration Sometimes you need to get a list of all the elements of a -class at run time. For these purposes, the compiler creates a method in each -class . Usage example: enumenumpublic static EnumClass[] values()
System.out.println(Arrays.toString(Season.values()));
We get the following output:
[WINTER, SPRING, SUMMER, AUTUMN]
Note that neither method valueOf()nor method values()is defined in the class java.lang.Enum. Instead, they are automatically added by the compiler when enumthe -class is compiled. Adding your own methods to enumthe -class You have the opportunity to add your own methods both to the enum-class and to its elements: Enumerations in Java (java enum) - 2The same, but with polymorphism: Enumerations in Java (java enum) - 3The last example demonstrates the use of inheritance in enum. More on this later. Inheritanceenum in Java enumallows you to implement a class hierarchy, the objects of which are created in a single instance and are statically accessible. In this case, elements enumcan contain their own constructors. Let's give an example: Enumerations in Java (java enum) - 4Here we declare an enumeration Typewith three elements INT, INTEGERand STRING. The compiler will create the following classes and objects:
  • Type- class derived fromjava.lang.Enum
  • INT— object of the 1st class derived fromType
  • INTEGER— object of the 2nd class derived fromType
  • STRING— object of the 3rd class derived fromType
Three derived classes will be created with a polymorphic method Object parse(String)and constructor Type(..., boolean). At the same time, objects of classes INT, INTEGERand STRINGexist in a single copy and are statically accessible. You can verify this:
System.out.println(Type.class);
System.out.println(Type.INT.getClass() + " " + Type.INT.getClass().getSuperclass());
System.out.println(Type.INTEGER.getClass() + " " + Type.INTEGER.getClass().getSuperclass());
System.out.println(Type.STRING.getClass()  + " " + Type.STRING.getClass().getSuperclass());
We get the following output:
class Type
class Type$1 class Type
class Type$2 class Type
class Type$3 class Type
It can be seen that the compiler created a class Typeand 3 nestedclasses derived from Type.

Decompiled enum-class with inheritance

To confirm the above, we also present the result of decompiling the enumeration Typefrom the example above: Enumerations in Java (java enum) - 5

Enumerations and parametric polymorphism

The reader may wonder: " Why doesn't the above Type enumeration use generics? " The fact is that in Java the use of generics is enumprohibited. So the following example will not compile:
enum Type<T> {}

Further Study

For a deeper understanding of how enumerations work in Java, I recommend that you familiarize yourself with the source code of the class java.lang.Enum, and also use the Jad decompiler to study the generated code. Moreover, studying the Java library source code is absolutely necessary for understanding how many of the mechanisms in Java work and is useful as a reference for object-oriented design. Link to the original source: http://alexander.lds.lg.ua/
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION