While reading about constant interface antipattern, i found final constant class with no instances is better than constant interface.
Please explain me how?
public interface ConstIfc {
public static final int constValue = 10;
}
public final class ConstClass {
private ConstClass{}
public static final int constValue = 10;
}
If constValue has to be used in a UtilClass without naming of Ifc/Class name we can implement/extends those. but implements supports multiple inheritance. So how extends better?
Note: I’m able to understand static import.
Interfaces are an abstraction, and to remain abstract, they should not contain implementation details (including constant variables.) Interfaces also are often used to describe a public API, in which implementation details do not belong. For this reason it makes sense to put constant data into a class, rather than an interface.
I’m not sure what you mean by “how extends better?”, but I think you should avoid inheriting / extending this sort of implementation detail into multiple classes. Improperly leveraging implementation inheritance often leads to inflexible design. In your example, the
finalkeyword onConstClassutilizes the compiler to prevent you from doing this, which is not possible with an interface.