Monday, 11 April 2016

Java Enum Example with Constructor

Java Enum with Constructor
Java Enum can have Constructor to pass data while creating Enum constants. 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 associate with stop and ORANGE is associated with slow down. You can also provide one or more constructor to your Enum as it also support constructor overloading. Just note that modifierpublic and protected are not allowed to Enum constructor, it will result in compile time error. By the way We have covered see some enum examples in our previous posts e.g. Java Enum Switch Example, Java Enum valueOf Example and Enum to String Exmaple in Java, which is good to learn 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 our TrafficLight constructor accept an String argument which is saved to action field which is later accessed by getter method getAction().

/**
 * 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 can not
 * be public or protected
 *
 * @author http://java67.blogspot.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 constructor in Java which can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor can not be protected or public, it can either have private or default modifier only.

Other Java 5 tutorial you may like

Java 5 new features list



TAGS :     JAVA          JAVA TUTORIAL           JAVA STUDY ONLINE

No comments:

Post a Comment