Java Enumeration Type Add constructor to enum type

Introduction

A Java enumeration is a class type.

We can add constructors, instance variables and methods, and even implement interfaces on Java enum types.

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.

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

  private int value; 

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

  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() + ".");
    }
      
  }
}
// Declare an enum type with constructor and explicit instance fields and accessors for these fields
// Testing enum type Book.
import java.util.EnumSet;
enum Book/*  w  w  w.  j  av  a 2s.  co  m*/
{    
   // declare constants of enum type                                
   JAVA("Java", "2015"),                        
   C("C", "2013"),                           
   CSS("CSS", "2012"),
   CPP("C++", "2014"),                       
   JAVASCRIPT("Javascript", "2014"),
   CSHARP("C#", "2014");

   // instance fields 
   private final String title; 
   private final String copyrightYear;

   // enum constructor
   Book(String title, String copyrightYear) 
   { 
      this.title = title;
      this.copyrightYear = copyrightYear;
   } 

   // accessor for field title
   public String getTitle()
   {
      return title;
   } 

   // accessor for field copyrightYear
   public String getCopyrightYear()
   {
      return copyrightYear;
   } 
} 


public class Main 
{
   public static void main(String[] args) 
   {
      // print all books in enum Book                          
      for (Book book : Book.values())                        
         System.out.printf("%-10s%-45s%s%n", book,
             book.getTitle(), book.getCopyrightYear());

      System.out.printf("%nDisplay a range of enum constants:%n");
    
      // print first four books                                 
      for (Book book : EnumSet.range(Book.JAVA, Book.CPP))
         System.out.printf("%-10s%-45s%s%n", book,
             book.getTitle(), book.getCopyrightYear());
   } 
}



PreviousNext

Related