Enum (Enumerations) in Java, with Examples
Learn what enums are in Java, how they work as special classes, and how to add attributes and private constructors, with football examples.
You can download the project for this post by clicking HERE.
An enumeration (or Enum) is a "special" class (in Java as well as in other languages) that limits the creation of objects to those explicitly specified in the class implementation. The only limitation enums have compared to a normal class is that if they have a constructor, it must be private so that no new objects can be created.
Let’s start with a simple example of an Enum class. Going back to the football-related examples, football players are characterized by a position when playing a match, so the positions a player can play in are finite and can be listed as: Goalkeeper, Defender, Midfielder and Forward. With this specification we can create the following "Enum" class called "Demarcacion":
public enum Demarcacion
{
PORTERO, DEFENSA, CENTROCAMPISTA, DELANTERO
}
By convention (although you can name them however you like) enum names are written in uppercase.
It is very important to understand that an "Enum" in Java is really a class (whose objects can only be the ones defined in that class: PORTERO, …, DELANTERO) that inherits from the "Enum (java.lang.Enum)" class, and therefore enums have a series of methods inherited from that parent class (Click HERE to see its JavaDoc). Below we show some of the most commonly used enum methods:
public enum Demarcacion{PORTERO, DEFENSA, CENTROCAMPISTA, DELANTERO}
Demarcacion delantero = Demarcacion.DELANTERO; // Instancia de un enum de la clase Demarcación
delantero.name(); // Devuelve un String con el nombre de la constante (DELANTERO)
delantero.toString(); // Devuelve un String con el nombre de la constante (DELANTERO)
delantero.ordinal(); // Devuelve un entero con la posición del enum según está declarada (3).
delantero.compareTo(Enum otro); // Compara el enum con el parámetro según el orden en el que están declarados lo enum
Demarcacion.values(); // Devuelve un array que contiene todos los enum
Now that we’ve seen the most commonly used enum methods, let’s look at an example to see the results these methods return. Given the following code snippet:
Demarcacion delantero = Demarcacion.DELANTERO;
Demarcacion defensa = Demarcacion.DEFENSA;
// Devuelve un String con el nombre de la constante
System.out.println("delantero.name()= "+delantero.name());
System.out.println("defensa.toString()= "+defensa.toString());
// Devuelve un entero con la posición de la constante según está declarada.
System.out.println("delantero.ordinal()= "+delantero.ordinal());
// Compara el enum con el parámetro según el orden en el que están declaradas las constantes.
System.out.println("delantero.compareTo(portero)= "+delantero.compareTo(defensa));
System.out.println("delantero.compareTo(delantero)= "+delantero.compareTo(delantero));
// Recorre todas las constantes de la enumeración
for(Demarcacion d: Demarcacion.values()){
System.out.println(d.toString()+" - ");
}
We get the following output:
delantero.name()= DELANTERO
defensa.toString()= DEFENSA
delantero.ordinal()= 3
delantero.compareTo(defensa)= 2
delantero.compareTo(delantero)= 0
PORTERO - DEFENSA - CENTROCAMPISTA - DELANTERO
As we’ve already said, an enum is a special class that limits the creation of objects to those specified in its class (that’s why its constructor is private, as you can see in the following code snippet); but these objects can have attributes like any other class. In the following class declaration, we see an example where we define an enum "Equipo" (team) that will have two attributes: the name and the position the team finished in the league in the 2009/2010 season.
public enum Equipo
{
BARÇA("FC Barcelona",1), REAL_MADRID("Real Madrid",2),
SEVILLA("Sevilla FC",4), VILLAREAL("Villareal",7);
private String nombreClub;
private int puestoLiga;
private Equipo (String nombreClub, int puestoLiga){
this.nombreClub = nombreClub;
this.puestoLiga = puestoLiga;
}
public String getNombreClub() {
return nombreClub;
}
public int getPuestoLiga() {
return puestoLiga;
}
}
As you can see, BARÇA, REAL_MADRID, etc. are the names of the enum constants (or objects of the Equipo class), which will have "nombreClub" and "puestoLiga" as attributes. As you can see in the class, we define a constructor that is private (meaning it is only visible inside the Equipo class) and we only define the "get" methods. Working with the attributes of these enums is done the same way as with any other object: you instantiate an object and access the attributes with the get methods. In the following code snippet we’ll see how to work with enums that have attributes:
// Instanciamos el enumerado
Equipo villareal = Equipo.VILLAREAL;
// Devuelve un String con el nombre de la constante
System.out.println("villareal.name()= "+villareal.name());
// Devuelve el contenido de los atributos
System.out.println("villareal.getNombreClub()= "+villareal.getNombreClub());
System.out.println("villareal.getPuestoLiga()= "+villareal.getPuestoLiga());
The output of this code snippet is the following:
villareal.name()= VILLAREAL
villareal.getNombreClub()= Villareal
villareal.getPuestoLiga()= 7
It’s very important that you are clear that enums are not Strings (although they can be), but objects of a class that can only be instantiated from the class where they are implemented, and that you cannot create an object of that class from anywhere other than inside that class. It’s very common (especially when you’re learning what enums are) to interpret an enum as a finite list of Strings, when in reality it is a finite list of objects of a given class with their attributes, constructor and getter methods, even if these are private.
Next we’ll look at a simple example where we combine the two previous enums (Demarcacion and Equipo). In this example (following the line of the examples in the posts on Inheritance, Polymorphism and Polymorphism II) we’ll create some objects of the Futbolista (football player) class, which will represent the players of the Spanish national team who won the World Cup in South Africa in 2010. This class characterizes the players by their name, their shirt number, the position they play and the football club they belong to, as we can see in the following class diagram.
As we can see, the position and team attributes are of the Demarcacion and Equipo classes respectively, and they are the enums we saw earlier; therefore a player can only belong to one of the four teams that make up the "Equipo" enum and can play in one of the four positions that make up the "Demarcacion" enum. Below we show the implementation of the "Futbolista" class:
package Main;
public class Futbolista {
private int dorsal;
private String Nombre;
private Demarcacion demarcacion;
private Equipo equipo;
public Futbolista() {
}
public Futbolista(String nombre, int dorsal, Demarcacion demarcacion, Equipo equipo) {
this.dorsal = dorsal;
Nombre = nombre;
this.demarcacion = demarcacion;
this.equipo = equipo;
}
// Getter and setter methods
................................
@Override
public String toString() {
return this.dorsal + " - " + this.Nombre + " - "
+ this.demarcacion.name() + " - " + this.equipo.getNombreClub();
}
}
Given this class, we can now create objects of the Futbolista class, as we show below:
Futbolista casillas = new Futbolista("Casillas", 1, Demarcacion.PORTERO, Equipo.REAL_MADRID);
Futbolista capdevila = new Futbolista("Capdevila", 11, Demarcacion.DEFENSA, Equipo.VILLAREAL);
Futbolista iniesta = new Futbolista("Iniesta", 6, Demarcacion.CENTROCAMPISTA, Equipo.BARÇA);
Futbolista navas = new Futbolista("Navas", 22, Demarcacion.DELANTERO, Equipo.SEVILLA);
As we can see, the position and the team they belong to can only be the ones declared in the enum class. If we call the "toString()" method declared in the Futbolista class, we can print the players’ data to the screen. Given the following code:
System.out.println(casillas.toString());
System.out.println(capdevila.toString());
System.out.println(iniesta.toString());
System.out.println(navas.toString());
And given the following "toString()" method
@Override
public String toString() {
return this.dorsal + " - " + this.Nombre + " - "
+ this.demarcacion.name() + " - " + this.equipo.getNombreClub();
}
We get the following output:
1 - Casillas - PORTERO - Real Madrid
11 - Capdevila - DEFENSA - Villareal
6 - Iniesta - CENTROCAMPISTA - FC Barcelona
22 - Navas - DELANTERO - Sevilla FC
In summary, this is everything important you need to know about enums in Java. In other programming languages enums may have more inherited methods, but the fundamental concept of an enum is that they are objects (and not Strings; although in Java a String is a class and not a primitive data type) defined in the same class with a private constructor, and if they have attributes, they only need "getter" methods to obtain the attribute’s value.
“Enum (Enumerations) in Java, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

You may also like
Advanced Dockerfile: Multi-Stage Builds, Registries, and Tricks
Free Docker course. Expert Docker tricks: multi-stage builds, optimizing images, faster build times, and distributing images through Docker registries.
Dockerfile: Directives and Dockerizing Projects
Free Docker course. A Dockerfile is a file of directives for building and deploying custom applications with Docker. Learn how to Dockerize your projects.




Leave a comment