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 ( ) The elements of an enumeration are instances
Elements
enum
. In Java, the enumeration did not appear immediately. A specialized language construct enum
has been introduced since version 1.5. Up to this point, programmers have used other methods to implement enums.
enum construct
Let's start with an example. Let's describe usingenum
the 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 declaringenum
, 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 enum
it 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 - enum
class, and the possible values of the enumerated type - elements enum
-a.
The elements of an enumeration are instances enum
of the -class that are statically available
Elements enum Season (WINTER, SPRING и т.д.)
are statically accessible instances enum
of 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, anyenum
-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 enum
by the string representation of its name Quite often, the problem arises of obtaining an element enum
by 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 EnumClass
with 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 name
equal 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, eachenum
enum
-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 enum
the -class You have the ability to add your own methods both to the enum
-class and to its members: Same, but with polymorphism: The last example demonstrates the use of inheritance in enum
. More on this later. Inheritance inenum
With enum
Java, you can implement a class hierarchy whose objects are created in a single instance and are available statically. However, elements enum
can contain their own constructors. Here is an example: An enum is declared hereType
with three elements INT
, INTEGER
and STRING
. The compiler will generate the following classes and objects:
Type
is 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
Object parse(String)
and a constructor Type(..., boolean)
. At the same time, objects of classes INT
, INTEGER
and STRING
exist 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 Type
and 3 nested
classes derived from Type
.
Decompiled enum-class with inheritance
In support of the above, here is the result of decompiling the enumerationType
from the example above:
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 isenum
prohibited. 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 classjava.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/
GO TO FULL VERSION