Java Enum Are Class Types


A Java enumeration is a class type.

We can define constructors, add instance variables and methods, and even implement interfaces.

Each enumeration constant is an object of its enumeration type.

When you define a constructor for an enum, the constructor is called when each enumeration constant is created.

Each enumeration constant has its own copy of any instance variables defined by the enumeration.


For example, consider the following version of Grade :

// Use an enum constructor, instance variable, and method.
enum Grade {
   A(10), B(9), C(8), D(7), E(6);

   private int value; // value of each Grade

   // Constructor
   Grade(int p) {
      value = p;

   int getValue() {
      return value;

public class Main {
   public static void main(String args[]) {
      Grade ap;

      // Display price of D.
      System.out.println("D value is " + Grade.D.getValue() + ".\n");

      // Display all Grades and values.
      System.out.println("All Grade values:");
      for (Grade a : Grade.values())
         System.out.println(a + " is " + a.getValue() + ".");

The output is shown here:


This version of Grade adds three things.

The first is the instance variable value, which is used to hold the value of each variety of Grade.

The second is the Grade constructor, which is passed the value of an Grade.

The third is the method getValue(), which returns the value of the grade.

When the variable ap is declared in main(), the constructor for Grade is called once for each constant that is specified.

Notice how the arguments to the constructor are specified, by putting them inside parentheses after each constant, as shown here:

A(10), B(9), C(12), D(15), E(8);

These values are passed to the p parameter of Grade(), which then assigns this value to value.

Again, the constructor is called once for each constant.

Because each enumeration constant has its own copy of value, you can obtain the value of a specified type of Grade by calling getValue().

For example, in main() the value of a D is obtained by the following call:


The values of all varieties are obtained by cycling through the enumeration using a for loop.

Because there is a copy of value for each enumeration constant, the value associated with one constant is separate and distinct from the value associated with another constant.