在Java中实现常量的最佳方法是什么? [英] What is the best way to implement constants in Java?
问题描述
我见过这样的例子:
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
并且假设我可以有一个Constants类来包装常量,声明它们静态决赛。我几乎不知道Java,我想知道这是否是创建常量的最佳方法。
and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.
推荐答案
这完全可以接受,甚至可能是标准。
That is perfectly acceptable, probably even the standard.
(public/private) static final TYPE NAME = VALUE;
其中 TYPE
是类型, NAME
是包含空格下划线的所有大写字母的名称, VALUE
是常量值;
where TYPE
is the type, NAME
is the name in all caps with underscores for spaces, and VALUE
is the constant value;
我强烈建议不要将常量放在自己的类或接口中。
I highly recommend NOT putting your constants in their own classes or interfaces.
作为附注:声明为final且可变的变量仍然可以更改;但是,变量永远不会指向不同的对象。
As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
例如:
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
这是合法的, ORIGIN
然后是(3,0)点。
That is legal and ORIGIN
would then be a point at (3, 0).
这篇关于在Java中实现常量的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!