Zu dieser Frage gibt es eine Reihe von Meinungen. Zunächst einmal werden Konstanten in Java im Allgemeinen als öffentlich, statisch und endgültig deklariert. Im Folgenden werden die Gründe dafür genannt:
public, so that they are accessible from everywhere
static, so that they can be accessed without any instance. Since they are constants it
makes little sense to duplicate them for every object.
final, since they should not be allowed to change
Ich würde niemals eine Schnittstelle für einen CONSTANTS-Zugriff bzw. ein CONSTANTS-Objekt verwenden, einfach weil von Schnittstellen im Allgemeinen erwartet wird, dass sie implementiert werden. Würde das nicht komisch aussehen?
String myConstant = IMyInterface.CONSTANTX;
Stattdessen würde ich zwischen verschiedenen Möglichkeiten wählen, die auf einigen kleinen Kompromissen beruhen, und so hängt es davon ab, was Sie brauchen:
1. Use a regular enum with a default/private constructor. Most people would define
constants this way, IMHO.
- drawback: cannot effectively Javadoc each constant member
- advantage: var members are implicitly public, static, and final
- advantage: type-safe
- provides "a limited constructor" in a special way that only takes args which match
predefined 'public static final' keys, thus limiting what you can pass to the
constructor
2. Use a altered enum WITHOUT a constructor, having all variables defined with
prefixed 'public static final' .
- looks funny just having a floating semi-colon in the code
- advantage: you can JavaDoc each variable with an explanation
- drawback: you still have to put explicit 'public static final' before each variable
- drawback: not type-safe
- no 'limited constructor'
3. Use a Class with a private constructor:
- advantage: you can JavaDoc each variable with an explanation
- drawback: you have to put explicit 'public static final' before each variable
- you have the option of having a constructor to create an instance
of the class if you want to provide additional functions related
to your constants
(or just keep the constructor private)
- drawback: not type-safe
4. Using interface:
- advantage: you can JavaDoc each variable with an explanation
- advantage: var members are implicitly 'public static final'
- you are able to define default interface methods if you want to provide additional
functions related to your constants (only if you implement the interface)
- drawback: not type-safe