Should a collection of constants be placed in a class or interface?

Viewed 19672

If I have a collection of static constants that I want to declare centrally so that they can be shared among various projects should they be put in a class or interface (Java).

In the past I have seen them mostly put in a class but I started thinking that since the class will not and should not be instantiated maybe they would be better in an interface, but then again the interface should not be implemented by any classes, e.g.

public class ErrorCodes {
    public static final String ERROR_1 = "-1";
    public static final String ERROR_2 = "-2";
}

or

public interface ErrorCodes {
    public static final String ERROR_1 = "-1";
    public static final String ERROR_2 = "-2";
}
10 Answers

Always use Interface to define only contract and Class to define implementation state (variable and constant) and behavior (method implementation)

Define Constants in Interface or Class

Read this article which explains advantages of defining constants in the class vs interface

Related