Java Enumeration Type Add default constructor for enum type

Introduction

An enum can offer two or more overloaded constructor.

// Use an enum constructor, instance variable, and method. 
enum Letter {//from  w ww. j a v a  2  s.  c  o m
  A(10), B(11), C(12), D(13), E(14), F;

  private int value; 

  // Constructor
  Letter(int p) {
    value = p;
  }

  // Constructor
  Letter() {
    value = -1;
  }
  
  int getValue() {
    return value;
  }
}

public class Main {
  public static void main(String args[]) {
    System.out.println("D: " + Letter.D.getValue() + "\n");

    for (Letter a : Letter.values()) {
      System.out.println(a + " is " + a.getValue() + ".");
    }
      
  }
}



PreviousNext

Related