kiki
kiki

Reputation: 13997

Java: Can interfaces contain constant variables defined in them?

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

Upvotes: 9

Views: 13736

Answers (3)

kuriouscoder
kuriouscoder

Reputation: 5582

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

Upvotes: 1

Kel
Kel

Reputation: 7780

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

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

Upvotes: 14

Related Questions