I know that in Java, someone can include constants inside interfaces by declaring them public static final
. However, suppose I have such an interface, called I
, which contains only public static final constants and no method signatures, and a class called C
. Why would I want to implement I in C? i.e. why would I do the following:
public class C implements I
Since the constants are public and static, wouldn't I be able to access them directly through I
?
As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class. And hence: Interfaces should only be used to define contracts and not constants!
To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.
In an interface, we're allowed to use: constants variables. abstract methods. static methods.
This (anti-)pattern is useful because it lets you use the names of those constants without having to prefix them with I.
. This used to be a common technique, but now that you can use import static
to import the constants the same way it's fallen out of favor. One of the reasons for avoiding it is that the set of constants really isn't an interface - it's just a bunch of values - and making it an interface lets you do bizarre things like writing
ConstantInterfaceWithNoMethods m = new ClassImplementingThatInterface;
or
if (m instanceof ConstantInterfaceWithNoMethods)
which just don't make sense in this context.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With