第一種使用接口:
-
public interface Constants{
-
public static final int AUDIT_STATUS_PASS = 1;
-
public static final int AUDIT_STATUS_NOT_PASS = 2;
-
}
第二種使用類:
-
public class Constans{
-
public static final int AUDIT_STATUS_PASS = 1;
-
public static final int AUDIT_STATUS_NOT_PASS = 2;
-
}
第三種使用枚舉:
-
public enum Constants {
-
AUDIT_STATUS_PASS(1),
-
AUDIT_STATUS_NOT_PASS(2);
-
private int status;
-
private Constants(int status){
-
this.setStatus(status);
-
}
-
public int getStatus() {
-
return status;
-
}
-
public void setStatus(int status) {
-
this.status = status;
-
}
-
}
第一種和第二種是一樣的,第一種寫起來更方便,不用public static final
,直接int AUDIT_STATUS_PASS = 1
就行。第三種好在能把說明也寫在裏面,比如
-
public enum Constants {
-
AUDIT_STATUS_PASS(1,"通過"),
-
AUDIT_STATUS_NOT_PASS(2,"退回");
-
private int status;
-
private String desc;
-
private Constants(int status,String desc){
-
this.setStatus(status);
-
this.desc = desc;
-
}
-
public int getStatus() {
-
return status;
-
}
-
public void setStatus(int status) {
-
this.status = status;
-
}
-
...
-
}
建議使用枚舉。《Effective Java》中也是推薦使用枚舉代替int
常量的。
枚舉當然是首選,另如果不用枚舉,在《Effective Java》一書中,作者建議使用一般類加私有構造方法的方式,至於爲什麼不用接口,那就要上升到語言哲學問題了。
-
public class Constants {
-
private Constants() {}
-
public static final int AUDIT_STATUS_PASS = 1;
-
public static final int AUDIT_STATUS_NOT_PASS = 2;
}