Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to define constants in an interface?

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?

like image 900
Jonathan Pitre Avatar asked May 15 '12 19:05

Jonathan Pitre


People also ask

Why constants should not be defined in interfaces?

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!

How do you declare a constant in an interface in Java?

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.

CAN interfaces have constant variables?

In an interface, we're allowed to use: constants variables. abstract methods. static methods.


1 Answers

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!

like image 168
templatetypedef Avatar answered Sep 29 '22 06:09

templatetypedef