10 Points about Enum in Java

Apart from Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent fixed number of things in a type-safe manner e.g. days of the week, days of the month, planets in solar system, buttons on remote control, keys on keyboard and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent fixed number of things, known as enum int pattern and enum string pattern. Though they serve the purpose, they had some major drawbacks, one of them was type-safety i.e. you cannot restrict them to represent fixed number of values  e.g. an integer constant, which is representing days of the week can have value as 100, which is incorrect, given we have only 7 days in a week.

These limitations are addressed by providing enum type, which guarantees that only correct and fixed number of values can be assigned to them. Good thing about Enum in Java is that they are feature rich, bad thing is that they are still under-used and many developers doesn't even know about Enumeration type in detail.

Though there are lot of blog post about different features of Enum in Java, and there usage, there is hardly any page, which provides a good look at key points about Enum. It doesn't mean to be comprehensive but at-least provides those lesser known details.

I had previously shared some features in form of question answer on my article 15 Java Enum Interview Questions and in this post we will learn more about Enum in Java, it's more like a summary and notes than a tutorial, which is meant to quickly realize power of Enumeration type in Java.




Enumeration Tutorial in Java

1) Enum are constants in Java. They are implicitly declared public, static and final. Since they are constant, there is no way you can change them.

2) All enumeration type implicitly extends from java.lang.Enum class internally. Which means Enums are internally represented as class type. Furthermore, enum constants are instances of the enumeration class. There are lot of similarity between enum and classes but there is also some difference e.g. enum instances are implicitly public static final, you don't need to declare them, just like shown in following slide :

Difference between Enum and Class in Java


3) Since all Enum type extends java.lang.Enum, they cannot extend any other class in Java, as multiple inheritance is not allowed in Java, and a class can only extend one class.

4) Enum can implement interface in Java, this is one way to extend enum type. When a Enum extend an interface, each of their instance implement interface method in their own way or you can provide a default implementation under Enum class itself. Take a look at this example, it's not the best but at-least demonstrate how to implement interface inside enum in Java.

public class EnumDemo04{

        public static void main(String args[]) {

                EnumThread thread = EnumThread.ONE;
                thread.run();

                thread = EnumThread.TWO;
                thread.run();

                thread = EnumThread.THREE;
                thread.run();

        }

       

        private enum EnumThread implements Runnable{

            ONE {
                @Override
                public void run() {
                       System.out.println("ONE");
                }
            },

            TWO {
                @Override
                public void run() {
                       System.out.println("TWO");
                }
            },

            THREE;

                @Override
                public void run() {
            System.out.println("Default");

                }
        }
}

Output
ONE
TWO
Default

You can see that EnumThread, which is an enum actually implements Runnable interface and also overrides run() method. This proves that enumeration type can not only implement interface but also can override methods in Java. To learn more about

5) An Enum class can have a constructor but it can only be private. You cannot make it public because Enum instances are supposed to be created at compile time and from the class itself. A non-private Enum constructor with any modifier other than private is a compile time error in Java. Though a constructor without any access modifier is also allowed. Similarly, you can also overload constructor inside Enum, as shown below, by the way don't forget to declare enum constants or ; before declaring constructors, you can also see this post to learn more about Enum constructor in Java.

public enum EnumWithConstructor{

                ;
                private EnumWithConstructor(){
                        System.out.println("Default no-arg Enum constructor");
                }             

                EnumWithConstructor(int i){
                        System.out.println("Enum Constructor with one argument");
                }
        
                // compile time error - illegal access modifier, only private is allowed
                public EnumWithConstructor(String s){
                        System.out.println("public constructor are not allowed inside Enum in Java");
                }

}

6) java.lang.Enum defines several useful methods, which is available to all enumeration type in Java. You can use name() method to get name of any Enum constants. String literal used to write enum constants are there name. Similarly values() method can be used to get an array of all Enum constants from an Enum type and you can use valueOf() method to convert any String to Enum constant in Java, as shown below

public class EnumDemo06{

        public static void main(String args[]) {
                Gender fromString =  Gender.MALE.valueOf("MALE");
                System.out.println("Gender.MALE.name() : " + fromString.name());
        }      

        private enum Gender{
                MALE, FEMALE;
        }

}

Output:
Gender.MALE.name() : MALE

In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling name on that returns "MALE".

7) There are two ways to compare enum constants in Java, you can either use equals() method or simply == operator. There are some advantages of using == operator over equals, as it provide type-safety and also avoid potential NullPointerException, if the enum on which you are calling equals() is null. You can see more details about comparing two Enums in Java here.

8) Enum constants cannot be cloned in Java. An attempt to make a clone of Enum constants will throw CloneNotSupportedException.

9) Like int, short and char, and String from Java 7, Enum can also be used inside switch and case statements, as shown below. You can also see this post to learn more about Enum and switch case in Java :

public class EnumDemo9{      

        public static void main(String args[]) {                            

                SmartPhone iPhone = new SmartPhone(SmartPhone.OS.iOS);
                SmartPhone.OS operatingSystem = iPhone.getOS();               

                switch(operatingSystem){
                case iOS:
                        System.out.println("Running on iOS");
                        break;                     

                case Android:
                        System.out.println("Running on Android");
                        break;

                case Windows8:
                        System.out.println("Running on Windows8");
                        break;
                }
        } 

}

class SmartPhone {       

        public enum OS{
                iOS, Android, Windows8;
        }

        private OS os;     

        public SmartPhone(OS os){
                this.os = os;          
        }   

        public OS getOS(){
                return os;

        }
}

Output:
Running on iOS
You can clearly say that we are using a enum variable inside switch() block to decision making, and we are also using enum constants in case statements.

10) When you declare an Enum type inside a class, it is by default static. You can see that from above example that, we can access OS Enum type as SmartPhone.OS, which is like accessing static member of any class.

11) new() operator is not permitted to be used with enum, not even inside enum itself. This is because, Enum constants are fixed, and no instance of enum can be created at runtime.

12) Like any other class, you can also override toString() method for any Enum type. By default toString() method returns name of Enum constants and its output is same as of name() method, but you can override it to provide more information.

Java Enum Tutorials and ExamplesThat's all about Enum in Java. I hope this detail help you to understand Enumeration type in Java. It's one of the fundamental concept, which you can't afford to overlook. Since I have used Java even before enumeration type exists, I can say that enum helps you to write robust and clean code in Java.

Hungry to learn more about Enumeration type? Check out this amazing Enum tutorials

  1. Java enum concepts and fundamentals for beginners (see here)
  2. How to convert enum to String in Java  (click here)
  3. How to use enum in switch case in Java (see here)
  4. How to loop over Enum constants using foreach loop in Java (link)
  5. How to use valueOf() method of Enum in Java (read here)
  6. How to create enum from String in Java (read here)
  7. Practical Example of Enum in Java (see here)
  8. How to define constructor for Enumeration type (read here)
  9. How to implement Singleton pattern using Enum in Java (check here)
  10. Difference between RegularEnumSet and JumboEnumSet (read here)
  11. 15 Questions to check your knowledge about Enum in Java (answers)

1 comment:

  1. The line :
    Gender fromString = Gender.MALE.valueOf("MALE");

    should be corrected to :

    Gender fromString = Gender.valueOf("MALE");

    ReplyDelete