我见过这样的例子:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}

假设我可以有一个Constants类来包装常量,并将它们声明为静态final。我几乎不知道Java,我想知道这是否是创建常量的最佳方式。


当前回答

在单独的类中创建静态final常量可能会给您带来麻烦。Java编译器实际上会对此进行优化,并将常量的实际值放置到引用它的任何类中。

如果你稍后更改了Constants类,并且没有对引用该类的其他类进行严格的重新编译,那么你最终将使用新旧值的组合。

不要把它们看作常量,而应该把它们看作配置参数,并创建一个类来管理它们。让值是非final的,甚至可以考虑使用getter。将来,当您确定其中一些参数实际上应该由用户或管理员进行配置时,这将变得容易得多。

其他回答

在Effective Java(第二版)中,建议对常量使用枚举而不是静态整型。

这里有一篇很好的关于Java中枚举的文章: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

请注意,在那篇文章的最后提出的问题是:

那么什么时候应该使用枚举呢?

答案为:

任何时候你需要一个固定的常数集

对于常量,Enum是一个更好的选择。这里有一个例子

公共类myClass {

public enum myEnum {
    Option1("String1", 2), 
    Option2("String2", 2) 
    ;
    String str;
            int i;

            myEnum(String str1, int i1) { this.str = str1 ; this.i1 = i }


}

I use static final to declare constants and go with the ALL_CAPS naming notation. I have seen quite a few real life instances where all constants are bunched together into an interface. A few posts have rightly called that a bad practice, primarily because that's not what an interface is for. An interface should enforce a contract and should not be a place to put unrelated constants in. Putting it together into a class that cannot be instantiated (through a private constructor) too is fine if the constant semantics don't belong to a specific class(es). I always put a constant in the class that it's most related to, because that makes sense and is also easily maintainable.

枚举是表示一组值的好选择,但是如果您要存储强调绝对值的独立常量(例如。TIMEOUT = 100 ms)你可以直接使用静态的final方法。

这完全可以接受,甚至可能是标准。

(public/private) static final TYPE NAME = VALUE;

其中TYPE是类型,NAME是全大写的名称,空格用下划线表示,VALUE是常量值;

我强烈建议不要将常量放在它们自己的类或接口中。

附注:声明为final且为mutable的变量仍然可以更改;但是,变量永远不能指向不同的对象。

例如:

public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}

这是合法的,ORIGIN将是(3,0)点。

单一的泛型常量类不是一个好主意。常量应该按照它们在逻辑上最相关的类来分组。

我建议您使用方法,而不是使用任何类型的变量(特别是枚举)。创建一个与变量同名的方法,并让它返回分配给变量的值。现在删除该变量,并将对它的所有引用替换为对刚才创建的方法的调用。如果您觉得常量足够通用,不应该为了使用它而创建类的实例,那么可以将常量方法作为类方法。