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

Enums in Java (java enum)

Published in the Random EN group
When programming, we often face 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 programming languages ​​with static typing provide a special data type - enumeration ( ) enum. In Java, the enumeration did not appear immediately. A specialized language construct enumhas been introduced since version 1.5. Up to this point, programmers have used other methods to implement enums. Enums in Java (java enum) - 1

enum construct

Let's start with an example. Let's describe using enumthe data type for storing the time of year:
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 the execution of which SUMMER will be displayed on the console . I think that the example is obvious and needs no explanation.

Enum is a class

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

The elements of an enumeration are instances enumof the -class that are statically available

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

The name and ordinal of the enum element

As mentioned earlier, any enum-class inherits java.lang.Enum, which contains a number of methods useful for all enums. Example:
Season season = Season.WINTER;
System.out.println("season.name()=" + season.name() + " season.toString()=" + season.toString() + " season.ordinal()=" + season.ordinal());
Will output:
season.name()=WINTER season.toString()=WINTER season.ordinal()=0
This shows the use of the name(), toString()and ordinal(). The semantics of the methods is obvious. It should be noted that these methods enum-class inherits from class java.lang.Enum. Retrieving an element enumby the string representation of its name Quite often, the problem arises of obtaining 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. 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 also be thrown . 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 runtime. For these purposes, eachenumenum-class, the compiler creates a public static EnumClass[] values(). Usage example:
System.out.println(Arrays.toString(Season.values()));
We get the output:
[WINTER, SPRING, SUMMER, AUTUMN]
Note that neither the method valueOf()nor the method values()is defined in the class java.lang.Enum. Instead, they are automatically added by the compiler during the enum-class compilation. Adding your own methods to enumthe -class You have the ability to add your own methods both to the enum-class and to its members: Enums in Java (java enum) - 2Same, but with polymorphism: Enums in Java (java enum) - 3The last example demonstrates the use of inheritance in enum. More on this later. Inheritance inenum With enumJava, you can implement a class hierarchy whose objects are created in a single instance and are available statically. However, elements enumcan contain their own constructors. Here is an example: Enums in Java (java enum) - 4An enum is declared hereTypewith three elements INT, INTEGERand STRING. The compiler will generate the following classes and objects:
  • Typeis a 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 a constructor Type(..., boolean). At the same time, objects of classes INT, INTEGERand STRINGexist in a single instance and are available statically. 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 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

In support of the above, here is the result of decompiling the enumeration Typefrom the example above: Enums in Java (java enum) - 5

Enums and parametric polymorphism

The reader might wonder: " why doesn't the above Type enum 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 enums work in Java, I recommend that you familiarize yourself with the source codes of the class java.lang.Enum, and also use the Jad decompiler to study the generated code. Moreover, studying the source codes of the Java library is absolutely necessary to understand how many of the mechanisms in Java work, and is useful as a benchmark 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