This article relies largely or entirely on a single source .(December 2025) |
In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. However, since constants are very often merely an implementation detail, and the interfaces implemented by a class are part of its exported API, this practice amounts to putting implementations details into the API, which was considered inappropriate by, e.g., Java designer Joshua Bloch. [1] In general, collecting system constants into classes independent of behaviour might create a poor object-oriented design because it is often a sign of low cohesion. For these reasons, constant interfaces may be considered an anti-pattern.
Use of this pattern has a few other downsides:[ original research? ]
Note that the Java libraries use constant interface pattern themselves. For example, the SwingConstants interface [2] was released in 1998, [3] and then it was a reasonable choice.
publicinterfaceConstants{doublePI=3.14159;doublePLANCK_CONSTANT=6.62606896e-34;}publicclassCalculationsimplementsConstants{publicdoublegetReducedPlanckConstant(){returnPLANCK_CONSTANT/(2*PI);}}publicinterfaceConstants{publicstaticfinalintCONSTANT=1;}publicclassClass1implementsConstants{publicstaticfinalintCONSTANT=2;// *publicstaticvoidmain(Stringargs[])throwsException{System.out.println(CONSTANT);}}Before the line marked with an asterisk is added, running Class1 prints 1. After adding the line, Class1 prints 2. Both versions compile without warnings or errors.
Many of the pitfalls of the anti-pattern can be avoided by converting the constant interface to a class with static attributes:
publicfinalclassConstants{privateConstants(){// restrict instantiation}publicstaticfinaldoublePI=3.14159;publicstaticfinaldoublePLANCK_CONSTANT=6.62606896e-34;}Since Java 5, one can use static import [4] to be able to use the constants without the Constants qualifier:
import staticConstants.PLANCK_CONSTANT;import staticConstants.PI;publicclassCalculations{publicdoublegetReducedPlanckConstant(){returnPLANCK_CONSTANT/(2*PI);}}The constants can also be imported en masse by using an import static Constants.* statement. This achieves the same goals as using an interface, allowing the constants to be referenced without a qualifier.
To varying degrees, the issues listed above have now been addressed:
Note, however, that the changes do nothing to improve the cohesion of the Constants class nor prevent the accidental silent modification of the value of a constant, so static imports should not be considered to be a panacea.