在JDK1.5 之前,我们定义常量都是: public static fianl.... 。现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。
public enum Color {
RED, GREEN, BLANK, YELLOW
}
面试题:请解释enum和Enum的区别
enum是一个关键字,使用enum定义个枚举类相当于继承了Enum这个类。
枚举中定义其他结构:
可以在枚举类中定义属性、方法或者实现接口。
package com.example.lonly;
interface IColor {
public String getColor();
}
enum Color implements IColor { // 实现IColor接口
RED("红色"), GREEN("绿色"), BLUE("蓝色");
// 如果定义很多内容,枚举对象必须写在第一行
private String title;
private Color(String title) { // 定义构造方法,绝对不能使用public
this.title = title;
}
public String toString() { // 覆写Object类中的toString方法
return this.title;
}
@Override
public String getColor() { // 实现接口中的方法
return this.title;
}
}
public class TestDemo {
public static void main(String[] args) {
IColor ic = Color.RED;
System.out.println(ic.getColor());
}
}
控制台输出:
红色