Search code examples
javaclass-constants

How do you define a class of constants in Java?


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 preferred way of doing this?

  1. Interface
  2. Abstract Class
  3. Final Class

Which one should I use and why?


Clarifications to some answers:

Enums - I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way.

Interface - I'm not going to set any class as one that implements the interface. Just want to use the interface to call constants like so: ISomeInterface.SOME_CONST.


Solution

  • Use a final class, and define a private constructor to hide the public one.
    For simplicity you may then use a static import to reuse your values in another class

    public final class MyValues {
    
      private MyValues() {
        // No need to instantiate the class, we can hide its constructor
      }
    
      public static final String VALUE1 = "foo";
      public static final String VALUE2 = "bar";
    }
    

    in another class :

    import static MyValues.*
    //...
    
    if (VALUE1.equals(variable)) {
      //...
    }