你如何在Java中定义一类常量? [英] How do you define a class of constants in Java?

查看:927
本文介绍了你如何在Java中定义一类常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您需要定义一个类,它所做的就是保持常量。

Suppose you need to define a class which all it does is hold constants.

public static final String SOME_CONST = "SOME_VALUE";

这样做的首选方式是什么?

What is the preferred way of doing this?


  1. 界面

  2. 抽象类

  3. 最终成绩

我应该使用哪一个?为什么?

Which one should I use and why?



澄清一些答案:

枚举 - 我不会使用枚举,我不会枚举任何内容,只是收集一些与之无关的常量彼此以任何方式。

Enums - I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way.

接口 - 我不打算将任何类设置为实现接口的类。只想使用接口来调用常量,如下所示: ISomeInterface.SOME_CONST

Interface - I'm not going to set any class as one that implements the interface. Just want to use the interface to call constants like so: ISomeInterface.SOME_CONST.

推荐答案

使用最后一堂课。
为简单起见,您可以使用静态导入在另一个类中重用您的值

Use a final class. for simplicity you may then use a static import to reuse your values in another class

public final class MyValues {
  public static final String VALUE1 = "foo";
  public static final String VALUE2 = "bar";
}

在另一个班级:

import static MyValues.*
//...

if(variable.equals(VALUE1)){
//...
}

这篇关于你如何在Java中定义一类常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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