Today I looked at the ZipEntry class and found the following:
public class ZipEntry implements ZipConstants, Cloneable
ZipConstants does not define any methods – only constants (static final int LOCHDR = 30)
It then occurred to me that implementing the interface with constants lets you access those constants directly, as if they were defined in the class itself. For example:
public interface Constants {
static final int CONST = 2;
}
public class implements Constants {
int doSomething(int input) {
return CONST * input;
}
}
Is there another reason not to use this, apart from:
- it is at first confusing where the constant is coming from
- it is considered wrong to use interfaces for constants definition
I’m curious because it is definitely not a very common practice.
Another reasons not to use this:
Since Java 5, there is a “clean” language feature that achieves the same goal: static imports.
Implementing interfaces to use constants is basically a pre-Java-5 hack to simulate static imports.