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

Enum in Java: how to use a class

Published in the Random EN group
Hello! In this article, I will tell you about Java Enums. Imagine that you were given the task: to 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: any text can be passed to the constructor of the DayOfWeek class . This way, someone will be able to create the day of the week "Frog", "Cloud", or "azaza322". This is clearly not the behavior that 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 ​​\u200b\u200bfor the “ day of the week ” class. Prior to 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 is worth paying 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 allowed the objects to be used 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 did much to solve the problem. We had 7 days of the week at our disposal, and at the same time no one could create new ones. This solution was suggested by Joshua Bloch in Effective Java . The book, by the way, is very cool and a must-read for any Java developer.
How to use the Enum class - 2
With the release of Java 1.5, the language has a ready-made solution for such situations - the Enum enum . Enum is also a class. But it is specially “sharpened” for solving problems similar to ours: creating some limited range of values. Because the creators of Java already had examples ready (say, the C language, in which Enum already existed), they were able to come up with the best option.

What is enum?

So what is an 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, indicated 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 the day mode determines what day it is today. 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 it’s not necessary: ​​the mechanism for 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 : 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 pre-Java 1.5 solution: the old solution could not be used with a switch .

What else do you need to know about the Enum class?

An enum class is a real class with all the possibilities that come with it. For example, if the current implementation of the 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 + '\'' +
               '}';
   }
}
Now our Enum constants have a title field , a getter, and an overridden toString method . Compared to ordinary classes, one serious limitation was imposed on Enum - it is impossible to inherit from it. In addition, enums have methods specific only to them:
  • values() : returns an array of all 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 of the constant. Counting 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 indicate the names of the elements of Enum in capital letters, because they are constants, and for them this is the notation, and not camelCase .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION