Il y a un certain nombre d'opinions pour répondre à cette question. Pour commencer, les constantes en Java sont généralement déclarées comme étant publiques, statiques et finales. Les raisons en sont les suivantes :
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
Je n'utiliserais jamais une interface pour un objet/accesseur CONSTANTS simplement parce que les interfaces sont généralement censées être implémentées. Cela ne serait-il pas amusant ?
String myConstant = IMyInterface.CONSTANTX;
Au lieu de cela, je choisirais entre plusieurs méthodes différentes, basées sur quelques petits compromis, et cela dépend donc de ce dont vous avez besoin :
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
1 votes
Juste pour ajouter constantes java : public/privé
0 votes
Similaire : Partager des chaînes constantes en Java entre plusieurs classes ?