我见过这样的例子:

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

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


当前回答

我这样做的方法之一是通过创建一个具有常量值的“全局”类,并在需要访问常量的类中进行静态导入。

其他回答

更进一步,您可以将全局使用的常量放在接口中,这样它们就可以在系统范围内使用。如。

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

但是不要执行它。只需在代码中通过完全限定类名直接引用它们。

我这样做的方法之一是通过创建一个具有常量值的“全局”类,并在需要访问常量的类中进行静态导入。

对于常量,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 }


}

我强烈建议不要只使用一个常量类。这在当时看起来是一个好主意,但是当开发人员拒绝记录常量,并且类增长到包含500个以上彼此完全不相关的常量(与应用程序的完全不同方面相关)时,通常会导致常量文件完全不可读。而不是:

If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+. If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant) If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.

一个好的面向对象设计不应该需要很多公开可用的常量。大多数常量都应该封装在需要它们完成工作的类中。