NOTE

enum

What enum is, how to use it, and a source-level look at java.lang.Enum.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

Used to define enumeration values. It is syntactic sugar implemented underneath through the Enum class.

2. How to Use It

enum Color
{RED, BLUE, GREEN}



class Test
{
    public static void main(String[] args)
    {
        System.out.println(Color.RED.name());//RED
        System.out.println(Color.RED.ordinal());//0
        System.out.println(Color.RED);//RED
        for (Color value : Color.values())
        {
            System.out.println(value);
        }
        System.out.println(Color.valueOf(Color.RED.name()));//RED

    }
}

3. Source Analysis

3.1. Enum

// An abstract class cannot be instantiated.
public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {// Serializable and comparable
        // The name of the enum constant; accessible through name()
        private final String name;
        // The order of the enum constant, starting from 0; accessible through ordinal()
        private final int ordinal;

}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub