Constant interface
double PLANCK_CONSTANT = 6.62606896e-34; }
public class Calculations implements Constants {
public double getReducedPlanckConstant() { return PLANCK_CONSTANT / (2 * PI); } } </source>
Example 2
public interface Constants {
public static final int CONSTANT = 1;
}
public class Class1 implements Constants {
public static final int CONSTANT = 2; // *
public static void main(String args[]) throws Exception {
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.
Alternatives
Many of the pitfalls of the anti-pattern can be avoided by converting the constants interface to a proper class with no instances:
public final class Constants {
private Constants() {
// restrict instantiation
}
public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
This still leaves the original intent of the pattern mostly un-addressed (i.e., there is no syntax for accessing the constants unqualified). However, since Java 5, consider using static import[1] to achieve the same goal:
import static Constants.PLANCK_CONSTANT;
import static Constants.PI;
public class Calculations {
public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}
The constants can also be imported en masse by adding a import static Constants.* statement. This achieves the same goals as using an interface, allowing the constants to be referenced without the namespace.
To varying degrees, the issues listed above have now been addressed:
- Because static members can be imported specifically, the class namespace need not be polluted with all members of the constants interface.
- Run-time and compile-time semantics are more closely aligned when using static imports instead of constants interfaces.
- The compiled code has one fewer binary compatibility constraint (that "class Calculations implements Constants").
- Because static imports apply only to the current file (and not the whole class hierarchy) it is easier to discover where each static member is declared.
- There is less need to declare variables of the constants interface type, and it is potentially clearer that no concrete instances actually exist.
Note however, the changes do nothing to improve the cohesion of the Constants class nor prevent the accidental silent modification of a constant's value, so static imports should not be considered to be a panacea.