Enums in Java

Enums in Java

Hi there. In this article I would be talking about working with enums in java and also take on some code examples on the application of enums.

Enums are special data types used to assign variables to a set of predefined constants. Enums are primarily used when we have a specific range of values to be assigned to a said variable.

For example, when stating the colour of the rainbow, we are usually restricted to the 7 constants (RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO and VIOLET) that represent the various colours and with enums we can define these colours and have a type secured way of representing these constants. Enums are singletons which means that only one option exists for the classloader and this functionality makes enums a good choice when working with code that requires fixed single choice options or for Switch statements.

We don't iniatialize enums with the new keyword like with regular classes but this doesn't stop it from being as powerful with its, ability to add instance variables and methods, implementation of interfaces, owning a constructor and ability to use Abstract class. Enums cannot extend other classes and its major difference to classes is that it is static and its declaration is final. Below is an example of a basic enum declaration

class Enum{  
//Defining the enum inside the class  
public enum RainbowColours { RED, YELLOW, GREEN, BLUE, INDIGO, VIOLETS}  
//Main method  
public static void main(String[] args) {  
//Reading the enum  
for (RainbowColours c : RainbowColours.values())  
System.out.println(c);  
}}

Working with Enums

Enums can be applied in several ways in java which makes it one of the easy Go-To option to most java developers

  • Defining enums inside and outside a class

Enums can function within and outside of a class in java. You define an enum type by using the enum keyword enum inside a class

class EnumA{  
enum Season { WINTER, SPRING, SUMMER, FALL; } //semicolon(;) is optional here  
public static void main(String[] args) {  
Season s=Season.WINTER;//enum type is required to access WINTER  
System.out.println(s);  
}}
  This returns an output of "WINTER" 

enum outside a class

enum Directions{ NORTH, SOUTH, EAST, WEST}  
class EnumB{  
public static void main(String[] args) {  
Directions d=Directions.WEST;  
System.out.println(d);  
}}
  This returns an output "WEST"
  • Running the main method inside an Enum
    enum Season {   
    WINTER, SPRING, SUMMER, FALL;  
    public static void main(String[] args) {  
    Season ss=Season.SPRING;  
    System.out.println(ss);  
    }  
    }
    
     This returns an output "SPRING"
    
  • Using a switch statement with enums

    class EnumC{  
    enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}  
    public static void main(String args[]){  
    Day day=Day.TUESDAY;  //Sets enum day to TUESDAY
    
    switch(day){  
    case SUNDAY:   
     System.out.println("Today is sunday");  
     break;  
    case MONDAY:   
     System.out.println("Today is monday");  
     break;
    case TUESDAY:   
     System.out.println("Today is tuesday");  
     break;  
    default:  
    System.out.println("other day");  
    }  
    }}
    
    This returns an output "Today is tuesday"
    
  • Specifying properties for enum constants

  public enum Enum //enum classes cant be initialized with key word "new" but can only be referenced since they are classloaded
  {
      GENDER("male","female"), CAT("lion","lioness"), BIRD("cock","hen");

      private final String Masculine; //must be set to private final because each variable has already been pre-set above in the enum declaration
      private final String Feminine;


       Enum(String masculine, String feminine){ //no public keyword because the contructor isn't public and sets the value properties of the enum constants.
           // This constructor sets the Properties of each enum constant
          this.Masculine=masculine;
          this.Feminine=feminine;

      }
      public String getMasculinity(){
          return Masculine;
      }
      public String getFemininity(){
          return Feminine;
      } //decide to use camel casing for a clearer description
  }

  //Running the enum above
  public class EnumTest {
      public static void main(String[] args){

          System.out.println("ennum values");
          for (EnumClass class : EnumClass.values()){ //Traversing enum 
              System.out.println("For class "+ class+ " the masculine form is "+ class.getMasculinity() + " and the feminine name is "+class.getFemininity());

          }



      }
  }
  This returns Multiple outputs starting with the first loop case "For class GENDER the masculine form is male and the feminine form is female"

The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself(since enums are set as final).

  • Displaying a set of enum constants

Enumset is one of the special implementations of a set for use with enumeration types. It is a special collection built to work with enum classes with methods such as "range", "of", "copyOf", "clone". Below is an example of an enum implementation that displays a range of enums from GENDER - BIRD.

import java.util.EnumSet;
  public enum Enum 
    {GENDER, CAT, BIRD;}
  public class EnumTest {
        public static void main(String[] args){

             System.out.println(EnumSet.range(EnumClass.GENDER,EnumClass.BIRD));

            }
     }

Java programming language enum types are much more powerful than their counterparts in other languages and java developers can use this to perform task in a simplified manner.

Hope this article has been of help to you and has helped you further understand how enums work. I would love to hear from you on further topics you would like me to cover via direct messaging. Also remember that we become better versions of ourselves by constantly failing and learning

WhatsApp Image 2022-10-16 at 3.00.34 AM.jpeg

Looking forward to hearing from you.

System.out.println("bye");