Can I can create public static final
variables in an interface? Can I keep some common constant values defined in these files?
Asked
Active
Viewed 1.4k times
9
-
Isn't this something that is trivial to simply *try*? You do have a working compiler, right? – Greg Hewgill Oct 25 '10 at 06: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 Oct 25 '10 at 06:03
-
possible duplicate of [Should a collection of constants be placed in a class or interface?](http://stackoverflow.com/questions/1372991/should-a-collection-of-constants-be-placed-in-a-class-or-interface) – Greg Hewgill Oct 25 '10 at 06:05
3 Answers
14
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.)

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
So then what is the solution? Define another class simply to define these constants? – kiki Oct 25 '10 at 06:01
-
@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. – Jon Skeet Oct 25 '10 at 06:02
-
1If you are implementing the interface only to avoid prefixing them with the interface name that is. – Maurice Perry Oct 25 '10 at 06:03
1
Yes, you can keep constants in interfaces. BTW, it's considered to be not very good practice.

Kel
- 7,680
- 3
- 29
- 39
1
Certainly, public
constants can be used declared inside interfaces. One thing, however, if your interface is just going to be placeholders for constants, use enum
instead

kuriouscoder
- 5,394
- 7
- 26
- 40