views:

62

answers:

3

Hi,

I am new to java, hence again another probably silly doubt.

I just want to know whether I can create public static final variables in an interface file. I know interfaces are abstract classes which contain methods that must be implemented by any class which implements the interfcae. But my question is whether I can keep some common constant values defined in these files?

Regards, Kiki

+5  A: 

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
So then what is the solution? Define another class simply to define these constants?
kiki
@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
If you are implementing the interface only to avoid prefixing them with the interface name that is.
Maurice Perry
+1  A: 

Yes, you can keep constants in interfaces. BTW, it's considered to be not very good practice.

Kel
+1  A: 

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