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 members are instances
Elements
enum
). Enumeration did not appear in Java right away. A specialized language construct enum
was introduced starting with version 1.5. Up to this point, programmers have used other methods to implement enumerations.
enum construct
Let's start with an example.enum
Let'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 declaringenum
, 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.Enum
us, it is still easy to verify that enum
it 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 enum
of a -class that are statically accessible
Elements enum Season (WINTER, SPRING и т.д.)
are statically accessible instances enum
of 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, anyenum
-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 enum
are inherited from the class java.lang.Enum
. Getting an element enum
by the string representation of its name Quite often the task arises of getting 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
. Please 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 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: enum
enum
public 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 enum
the -class is compiled. Adding your own methods to enum
the -class You have the opportunity to add your own methods both to the enum
-class and to its elements: The same, but with polymorphism: The last example demonstrates the use of inheritance in enum
. More on this later. Inheritanceenum
in Java enum
allows you to implement a class hierarchy, the objects of which are created in a single instance and are statically accessible. In this case, elements enum
can contain their own constructors. Let's give an example: Here we declare an enumeration Type
with three elements INT
, INTEGER
and 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
Object parse(String)
and constructor Type(..., boolean)
. At the same time, objects of classes INT
, INTEGER
and STRING
exist 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 Type
and 3 nested
classes derived from Type
.
Decompiled enum-class with inheritance
To confirm the above, we also present the result of decompiling the enumerationType
from the example above:
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 isenum
prohibited. 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 classjava.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/
GO TO FULL VERSION