How do you define a class of constants in Java?

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)) {
  //...
}

Leave a Comment