Java Learning Notes - Enumeration class enum

Reference resources:
https://www.runoob.com/java/java-enum.html
https://www.cnblogs.com/junFignting/p/14671771.html

Enum Class

1. Define format

A Java enumeration class is a special class that generally represents a set of constants. It is defined using the enum keyword, and each constant is divided by commas, as shown in the following examples:

enum Color 
{ 
    RED, GREEN, BLUE; 
} 

Each enumeration is implemented internally through Class, and all enumeration values are public static final.
The enumerated class Color transformation described above is implemented in the internal class, that is, RED, BLUE, GREEN are three instances of the Color class:

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

2. Use format

Enumeration classes can be declared either outside or inside the class.

Out of class:

enum Color
{
    RED, GREEN, BLUE;
}
 
public class Test
{
    // Execute Output Results
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Within class:

public class Test
{
    enum Color
    {
        RED, GREEN, BLUE;
    }
 
    // Execute Output Results
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Output of the above two pieces of code:

RED

Matters needing attention

1. Why can constructors in enumerated classes only be private? How do constructors in enumerations work?

Examples are as follows:

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

Output:

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

The constructor of an enumeration class can only be modified by the private keyword because the object calling the constructor is in Color, which is RED, GREEN, BLUE. When a Color class object is created, all instances in this enumeration class call the constructor, such as public static final Color RED = new Color();, So there will also be three outputs.

2. Why can't enumeration types use new to create instances?

Example:

Color c1 = Color.RED;

Since instances in an enumerated class are enumerated items in the class, only class names. enumerated items can be used outside the class.

3. Usage of enumerated classes in for() (iteratively enumerating elements)?

Example:

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

4. Use of enumerated classes in switch()?

Example:

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("gules");
        break;
      case GREEN:
         System.out.println("green");
        break;
      case BLUE:
        System.out.println("blue");
        break;
    }
  }
}

Enumeration class names, such as "case Color.RED:", cannot be used in a switch. Writing this is incorrect, and the compiler will determine each enumeration type based on the type of myVar in the switch. Enumeration options of the same type as myVar must be given directly in the case, but no more types.

5. Use of values (), ordinal (), and valueOf() methods?

enum-defined enumeration classes inherit the java.lang.Enum class by default and implement two interfaces, java.lang.Seriablizable and java.lang.Comparable.

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

  • values() returns all values in the enumeration class
  • ordinal() finds the index of each enumeration constant, just like an array index
  • valueOf() returns an enumeration constant for the specified string value

Example:

enum Color
{
    RED, GREEN, BLUE;
}
 
public class Test
{
    public static void main(String[] args)
    {
        // Call values()
        Color[] arr = Color.values();
 
        // Iterative Enumeration
        for (Color col : arr)
        {
            // View Index
            System.out.println(col + " at index " + col.ordinal());
        }
 
        // Use valueOf() to return an enumeration constant, non-existent error IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}

Output:

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

6. Enumerations can contain either concrete or abstract methods. If the enumeration class has an abstract method, each instance of the enumeration class must implement it.

Example:

enum Color{
    RED{
        public String getColor(){//Enumerate Objects to Implement Abstract Methods
            return "gules";
        }
    },
    GREEN{
        public String getColor(){//Enumerate Objects to Implement Abstract Methods
            return "green";
        }
    },
    BLUE{
        public String getColor(){//Enumerate Objects to Implement Abstract Methods
            return "blue";
        }
    };
    public abstract String getColor();//Define abstract methods
}

public class Test{
    public static void main(String[] args) {
        for (Color c:Color.values()){
            System.out.println(c.getColor());
        }
    }
}

Output:

gules
 green
 blue

Tags: Java Back-end

Posted on Thu, 11 Nov 2021 11:08:52 -0500 by moreshion