Monday, March 13, 2017

Java Enums, How to Use Them Correctly

When I learned about java enums (or enumerations), I thought that there was only one way of creating and using them in java programming language. The first time I have heard of enums was during a course called ICS 201 at KFUPM. In reality, they did not tell us about them. I just found about them while I was trying to solve problem related to showing day name in more than one language. Enums usually used to store static data that will never change through the life time of a program such as the name of days.

Before you continue with the lesson, Note that you must have the knowledge about the Following: 
  • Crating Java Files.
  • Using Main Class. 
  • Using Variables and Creating Objects.
  • Method Declaration.
  • Building Java Classes.
In this lesson we will be learning about the following:
  1. Java Enum Syntax.
  2. How to Travers All Enum Constants.
  3. Using Enum With Switch Statment.
  4. Customizing The Enum.

The Basic Syntax

There are two ways for creating enums in Java language, the easy way and the hard way. For now, let's talk about the easy way.

Suppose that a student is studying at university. The university classify students into 5 different categories, New Student, Freshman, Sophomore, Junior and Senior. We can use Java enum to store the values as follows:

public enum StudentLevel {
    NEW,FRESHMAN,SOPHOMORE,JUNIOR,SENIOR
}


This is the simplest way for creating enums in Java. The keyword 'enum' indecates that we are extending (or inherting from) the class Enum. This class is the base for all enumerated types in java language.

Now let's create new class and call it 'Student'. Inside our student class, we can have an attribute called 'level' which has the type 'StudentLevel'. We can set this attribute to any constant value that we have defined inside the "StudentLevel" enum.

public class Student {
    private StudentLevel level;
   
    public StudentLevel getLevel() {
        return this.level;
    }
   
    public void setLevel(StudentLevel level) {
        this.level = level;
    }

    public String toString(){
        return "Student Level: "+this.level;
    }
}


Finally, we create a min class to test how the code will work. We create an object of type student and set the level as follows:

public class Main{
    public static void main(String [] arguments){
        Student s = new Student();
        s.setLevel(StudentLevel.NEW);
        System.out.println(s);
    } 
}


When we run the program in NetBeans IDE, the output will be as follows:


Traversing Enum Values 

To print the values of all the constants inside the enum, we use the enhanced 'for' loop to do that. The following code snippet shows how its done.

public class Main{
    public static void main(String [] arguments){
        for(StudentLevel level : StudentLevel.values()){
            System.out.println(level);
        }
    } 
}

The Method 'values()' return an array that contains all the constants within the given enum. This program will show the following in the console:


Using The Enum With 'Switch' Statment

Most of the time, the enums are used within switch statement. We will use the same example that we used above to illestrate how to use the enum with switch statement. Depending on the assigned value for the attribute 'level', we can do different things.

public class Main{
    public static void main(String [] arguments){
        Student s = new Student();
        s.setLevel(StudentLevel.SENIOR);
       
        switch(s.getLevel()){
            case NEW:{
                System.out.println("Welcom to the university.");
                break;
            }
           
case FRESHMAN:{
                System.
out.println("Do your best, You still have 4 more years to go");
               
break;
            }
           
case SOPHOMORE:{
                System.
out.println("Finsh this year and you will be graduated in 3 years.");
                break;
            }
           
case JUNIOR:{
                System.
out.println("Two more years left");
               
break;
            }
           
case SENIOR:{
                System.
out.println("You did work hard. This is your final year!!");
               
break;
            }
        }
    } 
}



Customizing Enums

So far, we have seen the basic use of enum. But what if we would like to add more extra information inside the enum? For example, we may need to associate a range of credit hours for each level. This can be done by creating a constructor inside the enum that accepts parameters. By default, java provide an empty constructor for the enum. Now let's modify our basic enum and create a custom constructor in addition to the attributes that we need.

What we will do is to create a constructor that accepts 3 parameters, a name of type string and two other parameters of type integer. The name is just used to change how the name of the constant appears. By default, it appears in the way we define it. For example, if the name of the constant is 'SuNdAY', it will show as 'SuNdAY' in the console. By overriding the "toString()" method, we can change this.

Also we will create methods inside the enum to access the new attributes.

public enum StudentLevel {
    NEW("New Student",0,15),
    FRESHMAN("Freshman",16,45),
    SOPHOMORE("Sophomore",46, 70),
    JUNIOR("Junior",71, 90),
    SENIOR("Senior",91,132)
    //notice the semicolon here instead of a comma
    ;
    //the keyword final is optional
    private final int minCH, maxCH;
    private final String name;
   
    private StudentLevel(String name,int minCreditHours, int maxCreditHours){
        this.name = name;
        this.minCH = minCreditHours;
        this.maxCH = maxCreditHours;
    }
   
    public int getMinCreditHours(){
        return this.minCH;
    }
   
    public int getMaxCreditHours(){
        return this.maxCH;
    }
   
    public String value(){
        return this.name;
    }
   
    public String toString(){
        return this.name+", Min Credits: "+this.minCH+", Max Credits: "+this.maxCH;
    }
}


So, what did we do to create this custom enum? We did the following:
  • Replace the default enum constructor with custom one.
  • For each constant, we have added the extra attributes as if we where calling a method.
  • To do that, we added semicolon after the last enum constant.
  • The things that come after the semicolon is similar to any java class declaration.
  • We can add methods, attributes and to any other thing inside.
Now if we loop through the constants of the enum, we will see something different from what we have seen before. The reason for that is because we created our own custom 'toString()' method.



We can even do more if we would like since we are working with the enum as class. For example, we may make our enum implement java interfaces.


No comments:

Post a Comment

Feel free to write any thing in your mind here 😉