Enum Constant Implicit Methods

This section describes 2 static methods implicitly added by the Java compiler to all enum types declared by the 'enum' statement.

When you define an enum type with an "enum" declaration statement, the Java compiler implicitly adds two static method in the resulting class.

1. "public static E valueOf(String name)" - Returning the enum constant of this enum type with the specified name. This method is equivalent to the "public static E valueOf​(Class<E> enumType, String name)" static method defined in the base class java.lang.Enum<E>.

2. "public static E[] values() " - Returning an array of this enum type containing all enum constants declared in this enum type.

Note that those implicit methods are not mentioned in JDK API documentation. You have to read the Java language specification to find them.

Here is a sample program that shows you how to invoke methods listed above:

/* EnumImplicitMethods.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.lang.Enum;
class EnumImplicitMethods {
   enum Rank { GOLD, SILVER, BRONZE; }
   public static void main(String[] arg) {
      java.io.PrintStream out = System.out;
      out.println("Enum type implicit static methods:");
      out.println("   Rank.valueOf() = "+Rank.valueOf("GOLD"));
      out.println("   Rank.values() =");
      for (Rank r : Rank.values()) out.println("      "+r);
   }
}

If you compile and run EnumImplicitMethods.java, you should get:

herong> java EnumImplicitMethods.java

Enum type implicit static methods:
   Rank.valueOf() = GOLD
   Rank.values() =
      GOLD
      SILVER
      BRONZE

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

Enum Types and Enum Constants

 What Is an Enum Type

 Use 'class' to Define Enumeration

 Instance Variables for Enum Constants

 java.lang.Enum Super Type

 Enum Constant Inherited Methods

Enum Constant Implicit Methods

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials

 References

 Full Version in PDF/EPUB