Java Enum With Constructor Example

Java Enum with Constructor
Many Java developers don't know that Java Enum can have a constructor to pass data while creating Enum constants. This feature allows you to associate related data together. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass action to each Enum instance e.g. GREEN is associate with go, RED is associated with stop and ORANGE is associated with the slow down. This is really useful because it provides more context and meaning to your code. If you want, you can also provide one or more constructor to your Enum as it also supports constructor overloading like normal Java classes. This is very different from enum you have seen in C or C++, which is just a collection of fixed thing without any OOP power.

Just remember that constructor in enums an only be either private or package level it can't be public or protected hence access modifier public and protected are not allowed to Enum constructor, it will result in compile time error.

By the way, this is not our first tutorial on Java Enum where we have explained a key feature, we have also ready covered some important features on Enum in our previous examples like Java Enum Switch Example explains that you can use enum constants inside switch block.

Similarly, Java Enum valueOf Example and Enum to String Example in explains that how you can get the String representation of Enum. These short tutorials are a good way to learn some useful features of enum in Java.




Java Enum with Constructor Example

Java Enum with constructor example tutorialHere is complete code example of using Constructor with Java Enum. Here is our TrafficLight constructor accepts a String argument which is saved to action field which is later accessed by getter method getAction().

As I explained, we have an Enum TrafficSignal, which have three enum constants, RET, GREEN, and ORANGE, and we have associated, wait, go and slow down with them by passing values into the constructor.
Java Enum with Constructor Example




/**
 * Java enum with constructor for example.
 * Constructor accept one String argument action
 */

public enum TrafficSignal{
    //this will call enum constructor with one String argument
    RED("wait"), GREEN("go"), ORANGE("slow down");
 
    private String action;
 
    public String getAction(){
        return this.action;
    }
 
    // enum constructor - can not be public or protected
    TrafficSignal(String action){
        this.action = action;
    }
}

/**
 *
 * Java Enum example with constructor.
 * Java Enum can have constructor but it can not
 * be public or protected
 *
 * @author http://java67.com
 */

public class EnumConstructorExample{

    public static void main(String args[]) {
     
      //let's print name of each enum and there action
      // - Enum values() examples

      TrafficSignal[] signals = TrafficSignal.values();
   
      for(TrafficSignal signal : signals){
          //Java name example - Java getter method example
          System.out.println("name : "
                             + signal.name()
                             + " action: "
                             + signal.getAction());
      }
   
    }
 
}


This was our Java Enum example with Constructor. Now, you know that Enum can have a constructor in Java which can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor cannot be protected or public, it can either have private or default modifier only.


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
In-depth Guide of Enum in Java
10 Things Java Programmers Should Learn in 2018
How to become a better Java developer

Thanks for reading this article so far. If you like this short tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

1 comment:

  1. Hi,

    “Enum constructor can not be protected or public, it can either have private or default modifier only.”

    I am confused by reading above line??

    It is true we can’t declare enum constructor with public and protected modifier compiler gives you error.

    But as per line say we can declare constructor with “default” and “private” modifier.
    Means that enum constructor can have default modifier and we can do as below

    enum Color {
    RED.GREEN,BLUE;

    Color() {

    }

    public static void main(String[] args) {
    Color c = new Color();
    }

    }

    In the main method below line throws compile time error.
    Color c = new Color(); <- Color enum constructor is default compiler should allow this but isn’t.

    How compiler restricting this??

    So that i have check the differences of below two enum .class file and no single difference I found.
    Mean by default enum constructor are “private” If we don’t specify modifier.
    (I have done this because no way to find constructor modifier using reflection api or analysing .class syntax for modifier)


    enum Color {
    ;
    Color() {

    }
    }

    enum Color {
    ;
    private Color() {

    }
    }


    If we check the difference of below two java .class file code we will get the difference.
    class Test {
    Test() {

    }
    }

    class Test {
    private Test() {

    }
    }

    Mean if we don’t specify the modifier for enum constructor by default compiler is specify “private” so there is no default modifier concept for enum.
    Does my assumption is correct ??

    ReplyDelete