Menu
Topics Index
...
`

This program demonstartes the concept of constructor in an enum - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App