search
HomeJavajavaTutorialDetailed explanation of JAVA enumeration (enum)

Detailed explanation of JAVA enumeration (enum)

Jul 18, 2020 pm 05:35 PM
enumjavaenumerate

Detailed explanation of JAVA enumeration (enum)

Java enumeration is a special class that generally represents a set of constants, such as the 4 seasons of a year, the 12 months of a year, the 7 days of a week, and the direction Southeast, northwest, etc.

Java enumeration classes are defined using the enum keyword, and each constant is separated by commas.

For example, define a color enumeration class.

enum Color 
{ 
  RED, GREEN, BLUE; 
}

The color constants of the above enumeration class Color include RED, GREEN, and BLUE, which represent red, green, and blue respectively.

Usage example:

enum Color
{
  RED, GREEN, BLUE;
}
 
public class Test
{
  // 执行输出结果
  public static void main(String[] args)
  {
    Color c1 = Color.RED;
    System.out.println(c1);
  }
}

The output result of executing the above code is:

RED

Use enumeration in internal classes Example

The enumeration class can also be declared in the inner class:

public class Test
{
  enum Color
  {
    RED, GREEN, BLUE;
  }
 
  // 执行输出结果
  public static void main(String[] args)
  {
    Color c1 = Color.RED;
    System.out.println(c1);
  }
}

The output result of executing the above code is:

RED

Each enumeration is implemented internally through Class, and all enumeration values ​​are public static final.

The above enumeration class Color conversion is implemented in the internal class:

class Color
{
   public static final Color RED = new Color();
   public static final Color BLUE = new Color();
   public static final Color GREEN = new Color();
}

Iterate the enumeration elements

You can use the for statement to iterate the enumeration elements :

enum Color
{
  RED, GREEN, BLUE;
}
public class MyClass {
 public static void main(String[] args) {
  for (Color myVar : Color.values()) {
   System.out.println(myVar);
  }
 }
}

The output result of executing the above code is:

RED
GREEN
BLUE

Use enumeration in switch Enumeration class

The enumeration class is often used in switch statements:

enum Color
{
  RED, GREEN, BLUE;
}
public class MyClass {
 public static void main(String[] args) {
  Color myVar = Color.BLUE;

  switch(myVar) {
   case RED:
    System.out.println("红色");
    break;
   case GREEN:
     System.out.println("绿色");
    break;
   case BLUE:
    System.out.println("蓝色");
    break;
  }
 }
}

The output result of executing the above code is:

Blue

values(), ordinal() and valueOf() methods

The enumeration class defined by enum inherits the java.lang.Enum class by default and implements java. There are two interfaces: lang.Seriablizable and java.lang.Comparable.

values(), ordinal() and valueOf() methods are located in the java.lang.Enum class:

  • values() returns all values ​​in the enumeration class.
  • The ordinal() method can find the index of each enumeration constant, just like an array index.
  • The valueOf() method returns the enumeration constant of the specified string value.
enum Color
{
  RED, GREEN, BLUE;
}
 
public class Test
{
  public static void main(String[] args)
  {
    // 调用 values()
    Color arr[] = Color.values();
 
    // 迭代枚举
    for (Color col : arr)
    {
      // 查看索引
      System.out.println(col + " at index " + col.ordinal());
    }
 
    // 使用 valueOf() 返回枚举常量,不存在的会报错 IllegalArgumentException
    System.out.println(Color.valueOf("RED"));
    // System.out.println(Color.valueOf("WHITE"));
  }
}

The output result of executing the above code is:

RED at index 0
GREEN at index 1
BLUE at index 2
RED

Enumeration class members

Like ordinary classes, enumerations can use their own variables, methods and constructors. The constructor can only use the private access modifier. So it cannot be called externally.

Enumerations can contain both concrete methods and abstract methods. If an enumeration class has an abstract method, every instance of the enumeration class must implement it.

enum Color
{
  RED, GREEN, BLUE;
 
  // 构造函数
  private Color()
  {
    System.out.println("Constructor called for : " + this.toString());
  }
 
  public void colorInfo()
  {
    System.out.println("Universal Color");
  }
}
 
public class Test
{  
  // 输出
  public static void main(String[] args)
  {
    Color c1 = Color.RED;
    System.out.println(c1);
    c1.colorInfo();
  }
}

The output result of executing the above code is:

Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Recommended tutorial: "Java Tutorial"

The above is the detailed content of Detailed explanation of JAVA enumeration (enum). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:jb51. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor