9

Can I can create public static final variables in an interface? Can I keep some common constant values defined in these files?

3
  • Isn't this something that is trivial to simply try? You do have a working compiler, right? Commented 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. Commented Oct 25, 2010 at 6:03
  • possible duplicate of Should a collection of constants be placed in a class or interface? Commented Oct 25, 2010 at 6:05

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.