Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 240
kiki Avatar asked Oct 25 '10 05:10

kiki


People also ask

Can an interface have constant variables?

In an interface, we're allowed to use: constants variables. abstract methods. static methods.

Can interface contains constants in Java?

An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods.

Can we define variables in interface in Java?

You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.

CAN interfaces not have constants?

It's possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name.


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

like image 136
Jon Skeet Avatar answered Oct 05 '22 19:10

Jon Skeet