Menu
Topics Index
...
`
enum vs. switch

Till Java 1.4, allowed data types for switch argument were: byte, short, char, int.
But, from Java 1.5, corresponding wrapper classes for the above types (i.e., Byte, Short, Character and Integer respectively) and enum type could also be used.

Using enum type as argument in switch
enum Move
{
    LEFT,
    RIGHT,
    UP,
    DOWN;                
}

class EnumSwitchDemo
{
    public static void main(String arg[])
    {
        Move m1 = Move.DOWN;
        
        switch( m1 )   // LINE A
        {
            case LEFT: System.out.println( "You are going left" );
                                               break;
        
            case RIGHT: System.out.println( "You are going right" );
                                                break;
        
            case UP: System.out.println( "You are going up" );
                                             break;
        
            case DOWN: System.out.println( "You are going down" );
                                               break;
        
            default: System.out.println( "Invalid move" );
        }
              
    
    }
}
OUTPUT

You are going down

DESCRIPTION

Here, we are accessing the enum constant DOWN using the enum name Move. As we know, in enum, toString() is implicitly overridden to return its name. So, here m1 holds the enum constant DOWN. We are then passing it as an argument to switch (LINE A).

THINGS TO TRY
  • Try to access other enum constants as well in the same way and pass them as arguments to switch and observe the output.

  • If we pass enum type as argument to switch statement, then every case label must be a valid enum constant. Otherwise, we’ll get a compilation error.

For Example:
switch( m1 )
{
    case LEFT:
    case RIGHT:
    case UP:
    case DIAGONAL:     // Causes an error            
}
Compilation Error: unqualified enumeration constant name required

enum vs. constructor
  • enum can have a constructor which will be executed automatically at the time of enum class loading for every enum constant.
This program demonstartes the concept of constructor in an enum
enum Move
{
    LEFT, RIGHT, UP, DOWN;
    Move()
    {
                System.out.println( “enum constructor” );
    }
}

class EnumConstructorDemo
{
    public static void main(String arg[])
    {
        Move m1 = Move.DOWN;
        System.out.println( “Last Statement” );
    
    }
}
OUTPUT

enum constructor
enum constructor
enum constructor
enum constructor
Last Statement

DESCRIPTION

From the output, it is clear that enum constructor is executed separately for every enum constant.

THINGS TO TRY
  • Add another enum constant, say, DIAGONAL to the enum in the above example. Then compile it and observe that the constructor is executed five times this time around.

NOTE: We can’t explicitly create an object of enum type.
Move m1 = new Move();
Compilation Error: enum types may not be instantiated.

Let's now see the concept of methods in an enum.
Program to demonstrate the concept of constructors and methods in an enum
enum Bats
{
    MRF( 2000 ), ADIDAS( 1900 ), SG( 1500 ), BRITTANIA;
    int price;

    Bats( int price )
    {
        this.price = price;
    }

    Bats()
    {
        price = 1200;
    }

    public int getPrice()
    {
        return price;
    }
}

class EnumDemo
{
    public static void main(String arg[])
    {
        Bats[] m = Bats.values();
        for( Bats m1 : m )
        System.out.println( m1 + "-----" + m1.getPrice() );
    
    }
}
OUTPUT

MRF-----2000
ADIDAS-----1900
SG-----1500
BRITTANIA-----1200

DESCRIPTION

As every enum constant represents an object, all the methods that are applicable to an object can be applied on an enum constant as well i.e, an enum constant essentially behaves like an object.
Here, we have declared 2 constructors: default and parameterized. For enum constants MRF, ADIDAS, SG, parameterized constructor is executed with corresponding price value. In the main method, we are collecting enum constants in a Bats array and then iterating over the array by calling getPrice() on each enum constant.



  • Not only can we define methods on an enumerated type, but the implementation of the method can vary across instances.
Overriding methods for enum constants
enum Bats
{
    HERO, ADIDAS {
        public void info()      // LINE A
        {
            System.out.println( "Preferred by most of the players these days" );
        }
    }, SG;
    
    public void info()       // LINE B
    {
        System.out.println( "Preferred by some players" );
    }
}

class EnumDemo2
{
    Bats[] b = Bats.values();
    
    for( Bats b1 : b )
        b1.info();

}
OUTPUT

Preferred by some players
Preferred by most of the players these days
Preferred by some players

DESCRIPTION

In this example, the implementation of info() method is different for ADIDAS as we have overridden info() specifically for ADIDAS. So, for ADIDAS, overridden info() gets executed (LINE A). For HERO and SG, default info() gets executed (LINE B).

THINGS TO TRY
  • In the above program, try to define info() behavior specific to other enum constants as well and observe the change in the output.
  • Consider the program from enum vs. switch section. Try to use fully qualified names for switch case labels and see what happens i.e, Move.LEFT, Move.RIGHT etc.
  • We can have main() inside an enum in Java. Declare an enum named Bats with some enum constants and define main() inside it and then try to run the program using enum name.


0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App