Saturday, 19 October 2019

enum in Java

enum in Java

Enums are used when we know all possible values at compile time, such as choices on a menu.
In Java (from 1.5), enums are represented using enum data type.

In Java, we can also add variables, methods and constructors to it.The main objective of enum is to define our own data types(Enumerated Data Types).

Declaration of enum in java :

Enum declaration can be done outside a Class or inside a Class but not inside a Method.


// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
    RED, GREEN, BLUE;
}
  
public class Test
{
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
Output :
RED
// enum declaration inside a class. 
public class Test 
{ 
 enum Color 
 { 
  RED, GREEN, BLUE; 
 } 

 // Driver method 
 public static void main(String[] args) 
 { 
  Color c1 = Color.RED; 
  System.out.println(c1); 
 } 
}
First line inside enum should be list of constants and then other things like methods, variables and constructor.

Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can’t create child enums.

We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.


// A Java program to demonstrate that we can have 
// main() inside enum class. 
enum Color 
RED, GREEN, BLUE; 

// Driver method 
public static void main(String[] args) 
Color c1 = Color.RED; 
System.out.println(c1); 


Output :
RED
Enum and Inheritance :
  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
  • toString() method is overridden in java.lang.Enum class,which returns enum constant name.
  • enum can implement many interfaces.
enum and constructor :
  • enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.
  • We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.
enum and methods :
  • enum can contain concrete methods only i.e. no any abstract method.
// Java program to demonstrate that enums can have constructor
// and concrete methods.
  
// An enum (Note enum keyword inplace of class keyword)
enum Color
{
    RED, GREEN, BLUE;
  
    // enum constructor called separately for each
    // constant
    private Color()
    {
        System.out.println("Constructor called for : " +
        this.toString());
    }
  
    // Only concrete (not abstract) methods allowed
    public void colorInfo()
    {
        System.out.println("Universal Color");
    }
}
  
public class Test
{    
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}
Output:
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Enum with Customized Value in Java

By default enums have their own string values, we can also assign some custom values to enums.
  1. We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept.
  2. We have to create one getter method to get the value of enums.
// Java program to demonstrate how values can
// be assigned to enums.
enum TrafficSignal
{
    // This will call enum constructor with one
    // String argument
    RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN");
  
    // declaring private variable for getting values
    private String action;
  
    // getter method
    public String getAction()
    {
        return this.action;
    }
  
    // enum constructor - cannot be public or protected
    private TrafficSignal(String action)
    {
        this.action = action;
    }
}
  
// Driver code
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)
        {
            // use getter method to get the value
            System.out.println("name : " + signal.name() +
                        " action: " + signal.getAction() );
        }
    }
}
Output:
name : RED action: STOP
name : GREEN action: GO 
name : ORANGE action: SLOW DOWN 

    No comments:

    Post a Comment

    Note: only a member of this blog may post a comment.