常量类、常量接口和枚举

第一种使用接口:

  1. public interface Constants{

  2. public static final int AUDIT_STATUS_PASS = 1;

  3. public static final int AUDIT_STATUS_NOT_PASS = 2;

  4. }

第二种使用类:

  1. public class Constans{

  2. public static final int AUDIT_STATUS_PASS = 1;

  3. public static final int AUDIT_STATUS_NOT_PASS = 2;

  4. }

第三种使用枚举:

  1. public enum Constants {

  2. AUDIT_STATUS_PASS(1),

  3. AUDIT_STATUS_NOT_PASS(2);

  4.  
  5. private int status;

  6.  
  7. private Constants(int status){

  8. this.setStatus(status);

  9. }

  10.  
  11. public int getStatus() {

  12. return status;

  13. }

  14.  
  15. public void setStatus(int status) {

  16. this.status = status;

  17. }

  18.  
  19. }

第一种和第二种是一样的,第一种写起来更方便,不用public static final,直接int AUDIT_STATUS_PASS = 1就行。第三种好在能把说明也写在里面,比如

  1. public enum Constants {

  2. AUDIT_STATUS_PASS(1,"通过"),

  3. AUDIT_STATUS_NOT_PASS(2,"退回");

  4.  
  5. private int status;

  6. private String desc;

  7.  
  8. private Constants(int status,String desc){

  9. this.setStatus(status);

  10. this.desc = desc;

  11. }

  12.  
  13. public int getStatus() {

  14. return status;

  15. }

  16.  
  17. public void setStatus(int status) {

  18. this.status = status;

  19. }

  20. ...

  21. }

建议使用枚举。《Effective Java》中也是推荐使用枚举代替int常量的。

枚举当然是首选,另如果不用枚举,在《Effective Java》一书中,作者建议使用一般类加私有构造方法的方式,至于为什么不用接口,那就要上升到语言哲学问题了。

  1. public class Constants {

  2. private Constants() {}

  3. public static final int AUDIT_STATUS_PASS = 1;

  4. public static final int AUDIT_STATUS_NOT_PASS = 2;

  5. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值