Can I can create public static final variables in an interface? Can I keep some common constant values defined in these files?
-
Isn't this something that is trivial to simply try? You do have a working compiler, right?Greg Hewgill– Greg Hewgill2010-10-25 06:01:28 +00:00Commented Oct 25, 2010 at 6:01
-
I am sorry, I must rephrase. I have tried and it works. But I rather wanted to know if this is a good practice.kiki– kiki2010-10-25 06:03:07 +00:00Commented Oct 25, 2010 at 6:03
-
possible duplicate of Should a collection of constants be placed in a class or interface?Greg Hewgill– Greg Hewgill2010-10-25 06:05:19 +00:00Commented Oct 25, 2010 at 6:05
Add a comment
|
3 Answers
Yes, you can:
public interface Constants
{
public static final int ZERO = 0;
}
However, it's generally reckoned not to be a good idea these days. It's not so bad if the interface has a real purpose as well, and the constants are likely to be used by most of the implementations... but introducing an interface just to make it easier to get to constants is an abuse of the purpose of interfaces, really. (And that's what used to happen a lot.)
3 Comments
kiki
So then what is the solution? Define another class simply to define these constants?
Jon Skeet
@kiki: It depends on the situation. Sometimes enums work well instead of constants. Sometimes having them in a natural existing interface is as clean as anything else. Sometimes just keep them with the class that relates to them most strongly. Sometimes create a new class.
Maurice Perry
If you are implementing the interface only to avoid prefixing them with the interface name that is.