Menu
Topics Index
...
`

Program to demonstrate the concept of constructors and methods in an enum - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App