1.为什么要用枚举类型:
java思想是面向对象,封装的特性意味着尽量避免全局变量的定义,因为定义全局变量会增加代码的耦合性,但是代码的耦合又是不可能不存在的;那么定义全局变量的方式有几种呢?
(1)在接口中定义:因为接口中的属性默认被static final修饰的;
(2)在普通类中定义static final的变量;
(3)就是这里提到枚举类型,而且是最推荐使用的;
那么为什么推荐使用枚举类型来定义全局变量(Constant):枚举类型的速度要比静态类快很多
public enum Color {
RED("red", 1), BLUE("blue", 2), YELLOW("yellow", 3), WHITE("white", 4), BLACK("black", 5);
private String name;
private int index;
Color(String name, int index){
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
}