ENUMERATIONS IN JAVA
INTRODUCTION TO ENUMERATIONS
Let’s start by looking at this example.
An enumeration is declared and created through the keyword enum. Then we go on to enter the name we want to give our enum, as if it were a class. An enumeration in Java is an actual Data Type, if we want to be transparent, we have to say that he represents a somewhat special class. Within the body we define a set of constants. The elements of an enumeration are called enumerative constants, and in fact they are implicitly regarded as elements public and final. Let us see the test program in which we declare two variables of type size.
In addition, we can directly display the name of the variable t.
Finally, we can use enumerations to control a switch statement, let’s see the example.
ENUMS AS CLASSES
We have said that enumerations in Java are somewhat special classes, they can have constructors, attributes, and methods. Let’s look at an example.
The values passed to the constructor are enclosed in round brackets in the enumerative constants.
We added a numerical progressive to the categories representing sizes. See the main.
By the time we initialize the size with MEDIUM the constructors have already been invoked.
THE JAVA.LANG.ENUM CLASS
All enums are derived from a base class found in the java.lang package. When we talk about classification schemes, we can divide them into two major families,Ordinal and Nominal. See the figure.
Ordinal because they follow a certain order, SMALL is less than MEDIUM, LARGE is less than EXTRALARGE, similarly a degree follows an Ordinal classification, first comes the diploma then the degree. In the Nominal scheme there is no sorting criterion, it does not make sense to say that NORTH comes before SOUTH, that EAST comes before WEST etc. In all these cases we are enumerating a set of values but they are not ordered by each other.
TWO METHODS USED IN ENUMERATIONS
A first method we can use on enumerations is ordinal(), this method uses the arrangement of the constants in the enumeration and returns an int. It is based on the position of the constants; therefore, it is assumed that they are already ordered. CompareTo() returns a negative value if the value of the enumeration on which we invoke the method comes before the value passed as argument, zero if they are equal, greater than zero if the value of the enumeration on which we invoke the method comes after the value passed as argument.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON GITHUB
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CorsoJava.jar
- Or run the main found in the file CorsoJava.java.
Leave A Comment