枚举(enum)
主要是可以代替常量。比如
public class BasicsPersonConstant { public static final int TEACHER_CODE = "1"; public static final String TEACHER_DISPLAY = "教师"; public static final int STUDENT_CODE = "2"; public static final String STUDENT_DISPLAY = "学生"; public static final int PARENT_CODE = "3"; public static final String PARENT_DISPLAY = "家长"; }
实际上BasicsPersonConstant里面只想定义三个“概念”,这里可以用枚举代替
enum BasicsPerson { TEACHER(1, "教师"), STUDENT(2, "学生"), PARENT(3, "家长"); private Integer code; private String display; private BasicsPerson(Integer code, String display) { this.code = code; this.display = display; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } }
原先的BasicsPersonContant.STUDENT_CODE可以用 BasicsPerson.STUDENT.getCode()代替。
同时BasicsPerson.STUDENT可以作为一个对象来作为参数传递。
如果枚举仅仅作为区分用,可以不需要那些私有域。(这种情况可能)
enum BasicsPerson { TEACHER, STUDENT, PARENT; }