I am learning Java and just found that the Interface can have fields, which are public static and final. I haven’t seen any examples of these so far. What are some of the use cases of these Interface Constants and can I see some in the Java Standard Library?
Share
Putting static members into an interface (and implementing that interface) is a bad practice and there is even a name for it, the Constant Interface Antipattern, see Effective Java, Item 17:
To avoid some pitfalls of the constant interface (because you can’t prevent people from implementing it), a proper class with a private constructor should be preferred (example borrowed from Wikipedia):
And to access the constants without having to fully qualify them (i.e. without having to prefix them with the class name), use a static import (since Java 5):