From what I've read using interfaces to define constants is generally looked down upon in Java except when you intend constants to be inherited by classes implement the interface. But I've come across code like this often in Android programs:
interface Tags {
String BLOCK = "block";
String TITLE = "title";
String START = "start";
String END = "end";
String TYPE = "type";
}
Personally I like being able to group constants together like this into a namespace of sorts. So my question is there any disadvantage to doing this? I'm assuming it's probably not as efficient as using static final strings as the compiler can inline those.
It's possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name.
That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.
In an interface, we're allowed to use: constants variables. abstract methods. static methods.
The most common way to define a constant is in a class and using public static final . One can then use the constant in another class using ClassName. CONSTANT_NAME .
First, know that fields in an interface are implicitely static and final.
Constant interfaces are generally considered an anti-pattern (see http://en.wikipedia.org/wiki/Constant_interface). The better alternative would be:
public final class Tags {
public static final String BLOCK = "block";
// Other constants...
private Tags() {}
}
Since the Tags
class is final, no class can extend it. Instead, classes that want to use constants from Tags
simply do:
import my.package.Tags;
and then:
System.out.println(Tags.BLOCK);
From Java 5, the constants can be imported directly:
import static my.package.Tags.BLOCK;
// Other static imports...
so they can be used like so:
System.out.println(BLOCK);
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