java - 关于常量是使用常量类或者常量接口,还是使用枚举,有什么区别?

查看:681
本文介绍了java - 关于常量是使用常量类或者常量接口,还是使用枚举,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

关于常量,比如审核状态,1代表审核通过,2代表审核不通过


第一种使用接口:

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;
    }
    ...   
}

这篇关于java - 关于常量是使用常量类或者常量接口,还是使用枚举,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆