Can I can create public static final
variables in an interface? Can I keep some common constant values defined in these files?
In an interface, we're allowed to use: constants variables. abstract methods. static methods.
An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With