JavaRush /Java Blog /Random EN /Enum in Java: how to use the class

Enum in Java: how to use the class

Published in the Random EN group
Hello! In this article I will tell you about Java Enums. Imagine that you have been given a task: create a class that implements the days of the week . At first glance, there is nothing complicated about this, and your code will look something like this:

public class DayOfWeek {

   private String title;

   public DayOfWeek(String title) {
       this.title = title;
   }

   public static void main(String[] args) {
       DayOfWeek dayOfWeek = new DayOfWeek("Saturday");
       System.out.println(dayOfWeek);
   }

   @Override
   public String toString() {
       return "DayOfWeek{" +
               "title='" + title + '\'' +
               '}';
   }
}
And everything seems to be fine, but there is one problem: you can pass any text to the constructor of the DayOfWeek class. This way, someone can create the day of the week "Frog", "Cloud" or "azaza322". This is clearly not the behavior we expect, because there are only 7 real days of the week, and each of them has a name. Therefore, our task is to somehow limit the range of possible values ​​for the “ day of the week ” class. Before Java 1.5, developers were forced to come up with a solution to this problem on their own, since there was no ready-made solution in the language itself. In those days, if the situation required a limited number of values, they did this:

public class DayOfWeek {

   private String title;

   private DayOfWeek(String title) {
       this.title = title;
   }

   public static DayOfWeek SUNDAY = new DayOfWeek("Sunday");
   public static DayOfWeek MONDAY = new DayOfWeek("Monday");
   public static DayOfWeek TUESDAY = new DayOfWeek("Tuesday");
   public static DayOfWeek WEDNESDAY = new DayOfWeek("Wednesday");
   public static DayOfWeek THURSDAY = new DayOfWeek("Thursday");
   public static DayOfWeek FRIDAY = new DayOfWeek("Friday");
   public static DayOfWeek SATURDAY = new DayOfWeek("Saturday");

   @Override
   public String toString() {
       return "DayOfWeek{" +
               "title='" + title + '\'' +
               '}';
   }
}
What you should pay attention to here:
  • Private constructor. If a constructor is marked with the private modifier , an object of the class cannot be created using that constructor. And since there is only one constructor in this class, the DayOfWeek object cannot be created at all.

    
    	public class Main {
    
       		public static void main(String[] args) {
          
           			DayOfWeek sunday = new DayOfWeek();//error!
       		}
    }
  • At the same time, the class contained the required number of public static objects that were initialized in the way we needed (the names of the days are correct).

    This made it possible to use objects in other classes.

    
    	public class Man {
    
       		public static void main(String[] args) {
    
           			DayOfWeek sunday = DayOfWeek.SUNDAY;
    
           			System.out.println(sunday);
      		 }
    }

    Conclusion:

    DayOfWeek{title='Sunday'}

This approach largely allowed us to solve the problem. We had 7 days of the week at our disposal, and no one could create new ones. This solution was proposed by Joshua Bloch in the book Effective Java . The book, by the way, is very cool and a must-read for any Java developer.
How to use Enum class - 2
With the release of Java 1.5, the language introduced a ready-made solution for such situations - the Enum enumeration . Enum is also a class. But it is specially “tailored” to solve problems similar to ours: the creation of a certain limited range of values. Since the creators of Java already had ready-made examples (say, the C language, in which Enum already existed), they were able to create the optimal option.

What is enum?

So, what is Enum in Java ? Let's look at the example of the same DayOfWeek :

public enum DayOfWeek {

   SUNDAY,
   MONDAY,
   TUESDAY,
   WEDNESDAY,
   THURSDAY,
   FRIDAY,
   SATURDAY
}
It already looks much simpler :) Inside our Enum there are 7 constants with static access. We can already use it to implement logic in the program. For example, let's write a program that will determine whether a student needs to go to school today. Our student will have his own daily routine, designated by the ScholarSchedule class :

public class ScholarSchedule {

   private DayOfWeek dayOfWeek;
   //...other fields


   public DayOfWeek getDayOfWeek() {
       return dayOfWeek;
   }

   public void setDayOfWeek(DayOfWeek dayOfWeek) {
       this.dayOfWeek = dayOfWeek;
   }
}
The dayOfWeek variable in day mode determines what day it is. And here is our student’s class:

public class Scholar {

   private ScholarSchedule schedule;
   private boolean goToSchool;

   public void wakeUp() {
      
       if (this.schedule.getDayOfWeek() == DayOfWeek.SUNDAY) {
           System.out.println("Hooray, you can sleep some more!");
       } else {
           System.out.println("Damn, back to school :(");
       }
   }
}
In the wakeUp() method , using Enum, we determine the student’s further actions. We didn’t even describe in detail what each variable in DayOfWeek means , and this is not necessary: ​​the mechanism of the days of the week is already obvious, and if we use it in its current form, any developer will understand what is happening in your code. Another example of the convenience of Enum is that its constants can be used with a switch statement . For example, we are writing a program for a strict diet, in which meals are scheduled by day:

public class VeryStrictDiet {
   public void takeLunch(DayOfWeek dayOfWeek) {
       switch (dayOfWeek) {
           case SUNDAY:
               System.out.println("Sunday lunch! Today you can even have a little sweet");
               break;
           case MONDAY:
               System.out.println("Monday Lunch: Chicken Noodles!");
               break;
           case TUESDAY:
               System.out.println("Tuesday, today is celery soup :(");
               break;
               //...and so on until the end
       }
   }
}
This is one of the advantages of Enum over the old solution that was used before Java 1.5: the old solution could not be used with switch .

What else do you need to know about Enum class?

Enum class is a real class with all the capabilities that come with it. For example, if the current implementation of days of the week is not enough for you, you can add variables, constructors and methods to DayOfWeek :

public enum DayOfWeek {
  
   SUNDAY ("Sunday"),
   MONDAY ("Monday"),
   TUESDAY ("Tuesday"),
   WEDNESDAY ("Wednesday"),
   THURSDAY ("Thursday"),
   FRIDAY ("Friday"),
   SATURDAY ("Saturday");

   private String title;

   DayOfWeek(String title) {
       this.title = title;
   }

   public String getTitle() {
       return title;
   }

   @Override
   public String toString() {
       return "DayOfWeek{" +
               "title='" + title + '\'' +
               '}';
   }
}
Our Enum's constants now have a title field , a getter, and an overridden toString method . Compared to regular classes, Enum has one serious limitation - it cannot be inherited from. In addition, enumerations have methods unique to them:
  • values() : returns an array of all the values ​​stored in the Enum :

    
    public static void main(String[] args) {
       		System.out.println(Arrays.toString(DayOfWeek.values()));
    }

    Conclusion:

    [DayOfWeek{title='Sunday'}, DayOfWeek{title='Monday'}, DayOfWeek{title='Tuesday'}, DayOfWeek{title='Wednesday'}, DayOfWeek{title='Thursday'}, DayOfWeek{title= 'Friday'}, DayOfWeek{title='Saturday'}]

  • ordinal() : returns the ordinal number of a constant. The countdown starts from zero:

    
    	public static void main(String[] args) {
    
       		int sundayIndex = DayOfWeek.SUNDAY.ordinal();
       		System.out.println(sundayIndex);
    }

    Conclusion:

    0

  • valueOf() : Returns an Enum object corresponding to the given name:

    
    public static void main(String[] args) {
       DayOfWeek sunday = DayOfWeek.valueOf("SUNDAY");
       System.out.println(sunday);
    }

    Conclusion:

    DayOfWeek{title='Sunday'}

Pay attention:We capitalize the names of Enum elements because they are constants and are designated as such, not camelCase .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION