在 Java 中实现常量的最佳方法是什么? [英] What is the best way to implement constants in Java?
问题描述
我见过这样的例子:
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
并假设我可以有一个 Constants 类来包装常量,将它们声明为 static final.我几乎不知道 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屋!