How do you define a class of constants in Java?

后端 未结 10 2030
终归单人心
终归单人心 2020-12-07 12:44

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

10条回答
  •  無奈伤痛
    2020-12-07 13:25

    As Joshua Bloch notes in Effective Java:

    • Interfaces should only be used to define types,
    • abstract classes don't prevent instanciability (they can be subclassed, and even suggest that they are designed to be subclassed).

    You can use an Enum if all your constants are related (like planet names), put the constant values in classes they are related to (if you have access to them), or use a non instanciable utility class (define a private default constructor).

    class SomeConstants
    {
        // Prevents instanciation of myself and my subclasses
        private SomeConstants() {}
    
        public final static String TOTO = "toto";
        public final static Integer TEN = 10;
        //...
    }
    

    Then, as already stated, you can use static imports to use your constants.

提交回复
热议问题