Enum type with constructor and explicit instance fields and accessors for these fields - Java Language Basics

Java examples for Language Basics:enum

Description

Enum type with constructor and explicit instance fields and accessors for these fields

Demo Code

import java.util.EnumSet;
enum Book//from www. j  a  v a 2  s.co  m
{    
   // declare constants of enum type                                
   Java("Java", "2015"),                        
   C("C", "2013"),                           
   Internet("Internet", "2012"),
   Cpp("C++", "2014"),                       
   VB("Visual Basic", "2014"),
   CSharp("Visual 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) 
   {
      System.out.println("All books:");

      // 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());
   } 
}

Result


Related Tutorials