📜  Java中的枚举

📅  最后修改于: 2022-05-13 01:55:35.265000             🧑  作者: Mango

Java中的枚举

枚举的目的是在编程语言中表示一组命名常量。例如,一副扑克牌中的 4 个花色可能是 4 个枚举器,名称为 Club、Diamond、Heart 和 Spade,属于一个名为 Suit 的枚举类型。其他示例包括自然枚举类型(如行星、星期几、颜色、方向等)。

当我们在编译时知道所有可能的值时使用枚举,例如菜单上的选择、舍入模式、命令行标志等。枚举类型中的常量集不必一直保持固定

在Java (从 1.5 开始)中,枚举使用枚举数据类型表示。 Java枚举比 C/C++ 枚举更强大。在Java中,我们还可以为其添加变量、方法和构造函数。枚举的主要目标是定义我们自己的数据类型(枚举数据类型)。

Java中的枚举声明:枚举声明可以在类外部或类内部进行,但不能在方法内部进行。

Java
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
 
enum Color {
    RED,
    GREEN,
    BLUE;
}
 
public class Test {
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}


Java
// enum declaration inside a class.
 
public class Test {
    enum Color {
        RED,
        GREEN,
        BLUE;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}


Java
// A Java program to demonstrate working on enum
// in switch case (Filename Test. Java)
 
import java.util.Scanner;
 
// An Enum class
enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY;
}
 
// Driver class that contains an object of "day" and
// main().
public class Test {
    Day day;
 
    // Constructor
    public Test(Day day) { this.day = day; }
 
    // Prints a line about Day using switch
    public void dayIsLike()
    {
        switch (day) {
        case MONDAY:
            System.out.println("Mondays are bad.");
            break;
        case FRIDAY:
            System.out.println("Fridays are better.");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best.");
            break;
        default:
            System.out.println("Midweek days are so-so.");
            break;
        }
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "MONDAY";
        Test t1 = new Test(Day.valueOf(str));
        t1.dayIsLike();
    }
}


Java
// A Java program to demonstrate that we can have
// main() inside enum class.
 
enum Color {
    RED,
    GREEN,
    BLUE;
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}


Java
// Java program to demonstrate working of values(),
// ordinal() and valueOf()
 
enum Color {
    RED,
    GREEN,
    BLUE;
}
 
public class Test {
    public static void main(String[] args)
    {
        // Calling values()
        Color arr[] = Color.values();
 
        // enum with loop
        for (Color col : arr) {
            // Calling ordinal() to find index
            // of color.
            System.out.println(col + " at index "
                               + col.ordinal());
        }
 
        // Using valueOf(). Returns an object of
        // Color with given constant.
        // Uncommenting second line causes exception
        // IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}


Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.
 
// An enum (Note enum keyword inplace of class keyword)
enum Color {
    RED,
    GREEN,
    BLUE;
 
    // enum constructor called separately for each
    // constant
    private Color()
    {
        System.out.println("Constructor called for : "
                           + this.toString());
    }
 
    public void colorInfo()
    {
        System.out.println("Universal Color");
    }
}
 
public class Test {
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}


输出
RED

Java

// enum declaration inside a class.
 
public class Test {
    enum Color {
        RED,
        GREEN,
        BLUE;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
输出
RED
  • 枚举中的第一行应该是一个常量列表,然后是方法、变量和构造函数等其他内容。
  • 根据Java命名约定,建议我们将常量命名为全部大写

枚举的要点:

  • 每个枚举都是使用 Class 在内部实现的。
/* internally above enum Color is converted to
class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}*/
  • 每个枚举常量都代表一个枚举类型的对象
  • enum 类型可以作为参数传递给switch语句。

Java

// A Java program to demonstrate working on enum
// in switch case (Filename Test. Java)
 
import java.util.Scanner;
 
// An Enum class
enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY;
}
 
// Driver class that contains an object of "day" and
// main().
public class Test {
    Day day;
 
    // Constructor
    public Test(Day day) { this.day = day; }
 
    // Prints a line about Day using switch
    public void dayIsLike()
    {
        switch (day) {
        case MONDAY:
            System.out.println("Mondays are bad.");
            break;
        case FRIDAY:
            System.out.println("Fridays are better.");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best.");
            break;
        default:
            System.out.println("Midweek days are so-so.");
            break;
        }
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "MONDAY";
        Test t1 = new Test(Day.valueOf(str));
        t1.dayIsLike();
    }
}
输出
Mondays are bad.
  • 每个枚举常量总是隐含的public static final 。由于它是静态的,我们可以通过使用枚举名称来访问它。由于它是final ,我们不能创建子枚举。
  • 我们可以在枚举中声明main() 方法。因此,我们可以直接从命令提示符调用 enum。

Java

// A Java program to demonstrate that we can have
// main() inside enum class.
 
enum Color {
    RED,
    GREEN,
    BLUE;
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
输出
RED

枚举和继承:

  • 所有枚举都隐式扩展Java.lang.Enum 类。由于类只能扩展Java中的一个父级,因此枚举不能扩展其他任何东西。
  • toString() 方法Java.lang.Enum 类中被覆盖,它返回枚举常量名称。
  • enum 可以实现很多接口。

values()、ordinal() 和 valueOf() 方法:

  • 这些方法存在于Java.lang.Enum中。
  • values() 方法可用于返回枚举中存在的所有值。
  • 枚举中的顺序很重要。通过使用ordinal() 方法,可以找到每个枚举常量索引,就像数组索引一样。
  • valueOf() 方法返回指定字符串值的枚举常量(如果存在)。

Java

// Java program to demonstrate working of values(),
// ordinal() and valueOf()
 
enum Color {
    RED,
    GREEN,
    BLUE;
}
 
public class Test {
    public static void main(String[] args)
    {
        // Calling values()
        Color arr[] = Color.values();
 
        // enum with loop
        for (Color col : arr) {
            // Calling ordinal() to find index
            // of color.
            System.out.println(col + " at index "
                               + col.ordinal());
        }
 
        // Using valueOf(). Returns an object of
        // Color with given constant.
        // Uncommenting second line causes exception
        // IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}
输出
RED at index 0
GREEN at index 1
BLUE at index 2
RED

枚举和构造函数:

  • enum 可以包含一个构造函数,它在枚举类加载时为每个枚举常量单独执行。
  • 我们不能显式地创建枚举对象,因此我们不能直接调用枚举构造函数。

枚举和方法:

  • enum 可以包含具体方法和抽象方法。如果一个枚举类有一个抽象方法,那么这个枚举类的每个实例都必须实现它

Java

// Java program to demonstrate that enums can have
// constructor and concrete methods.
 
// An enum (Note enum keyword inplace of class keyword)
enum Color {
    RED,
    GREEN,
    BLUE;
 
    // enum constructor called separately for each
    // constant
    private Color()
    {
        System.out.println("Constructor called for : "
                           + this.toString());
    }
 
    public void colorInfo()
    {
        System.out.println("Universal Color");
    }
}
 
public class Test {
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}
输出
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

下一篇关于枚举的文章: Java中具有自定义值的枚举