Create enumerated constants in Java
What’s the advantage of a Java enum versus a class with public static final fields?
Why use Enums instead of Constants?
使用枚举和常量能都能达到同样的目的,那么它们之间的区别呢?使用枚举来表示常量,还是直接使用常量呢?
1、通常定义常量方法:public static final
public class Light {
public static final int RED = 1;
public static final int GREEN = 2;
public static final int YELLOW = 3;
}
2、枚举类型定义常量
public enum Light {
RED, GREEN, YELLOW;
}
上面代码我们只能表示出红灯、绿灯和黄灯,但是具体的值没有办法表示出来。由于枚举类型提供了构造函数,可以通过构造函数和覆写toString方法来实现。
首先给Light枚举类型增加构造方法,然后每个枚举类型的值通过构造函数传入,同时覆写toString方法,在该方法中返回构造函数中传人的参数,如下:
public enum Light {
// 利用构造函数传参数
RED(1), GREEN(2), YELLOW(3);
// 定义私有变量
private int code;
// 构造函数,枚举类型只能为私有
private Light(int _code) {
this.code = _code;
}
public String toString() {
return String.valueOf(this.code);
}
}