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;
}
第三种使用枚举:
第一种和第二种是一样的,第一种写起来更方便,不用
建议使用枚举。《Effective Java》中也是推荐使用枚举代替
枚举当然是首选,另如果不用枚举,在《Effective Java》一书中,作者建议使用一般类加私有构造方法的方式,至于为什么不用接口,那就要上升到语言哲学问题了。
public class Constants {
private Constants() {}
public static final int AUDIT_STATUS_PASS = 1;
public static final int AUDIT_STATUS_NOT_PASS = 2;
}
来源: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;
}
相关文章推荐
- Java中vector的使用详解、enumeration枚举接口的和iterator的区别、vector与list的对比
- Java 接口大全、面向接口编程、什么时候使用接口。选择Java接口还是抽象类
- 提高你的Java代码质量吧:推荐使用枚举定义常量
- 提高你的Java代码质量吧:推荐使用枚举定义常量
- Effective Java (3) 使用似有构造器或者枚举强化Singleton属性
- java.util.Queue接口add()和remove(),add()和remove(),element()或者peek()区别
- Java 接口大全、面向接口编程、什么时候使用接口。选择Java接口还是抽象类
- 常量接口 vs 枚举常量类
- Java 使用接口还是抽象?
- Java多线程实现接口Runnable和继承Thread区别(建议使用Runnable)
- java 基础总结 -- enum 枚举与接口、泛型、集合的使用
- Java 接口大全、面向接口编程、什么时候使用接口。选择Java接口还是抽象类
- JAVA中Arrays.sort()使用两种方式(Comparable和Comparator接口)对对象或者引用进行排序
- java 接口的定义,使用及和抽象类的区别
- Java 接口大全、面向接口编程、什么时候使用接口。选择Java接口还是抽象类
- 【JAVA中抽象类与接口的区别,分别在什么情况下使用它们】
- Java_类和对象(完美总结)_转载_覆盖和隐藏的区别,覆盖就不能使用了,而隐藏提供全局方法名或者全局变量名还可以使用
- Java 接口大全、面向接口编程、什么时候使用接口,选择Java接口还是抽象类
- 提高Java代码质量:使用枚举定义常量(转)
- Java 接口大全、面向接口编程、什么时候使用接口。选择Java接口还是抽象类