How do you define a class of constants in Java?

后端 未结 10 2034
终归单人心
终归单人心 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条回答
  •  Happy的楠姐
    2020-12-07 13:31

    enums are fine. IIRC, one item in effective Java (2nd Ed) has enum constants enumerating standard options implementing a [Java keyword] interface for any value.

    My preference is to use a [Java keyword] interface over a final class for constants. You implicitly get the public static final. Some people will argue that an interface allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.

    Which looks better?

    public final class SomeStuff {
         private SomeStuff() {
             throw new Error();
         }
         public static final String SOME_CONST = "Some value or another, I don't know.";
    }
    

    Or:

    public interface SomeStuff {
         String SOME_CONST = "Some value or another, I don't know.";
    }
    

提交回复
热议问题