Java-Enumeration Class Types

Enumeration Class Types

A Java enumeration is a class type. Although You don’t instantiate an enum using new, it otherwise has much the same capabilities as other classes. You have the possibility to add your own methods and fields when you define the enumeration type. You can also add your own constructors to initialize any additional fields you introduce.

It is important to understand that each enumeration constant is an object of its enumeration type. Thus, when you define a constructor for an enum, the constructor is called when each enumeration constant is created. Also, each enumeration constant has its own copy of any instance variables defined by the enumeration. For example, in the following program, the version of Fruits adds constructor. When accessing any Fruits constant in main( ), the constructor for Fruits is called once for each constant that is specified.



Program Source

enum Fruits {

    Apple, Banana, Cherry, Date, Elderberry;

    Fruits() {
        System.out.println("Constructer of : " + this.toString());

public class Javaapp {

    public static void main(String[] args) {

        Fruits fru = Fruits.Elderberry;

Leave a Comment