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 c开发者_Go百科lasses 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.
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);
精彩评论