您的位置:首页 > 编程语言 > Java开发

JAVA中常量使用常量类或者常量接口,还是使用枚举的区别

2017-07-27 17:23 513 查看
转载来源:最近在熟悉小组的代码时看见常量声明的不同方式就看了看这几种方式的不同之处。。

来源:https://segmentfault.com/q/1010000007620581?_ea=1406439


第一种使用接口:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐