I read “Effective Java” by Joshua Bloch and removed the ‘Constant Interface anti-pattern’ from our application. The trick is to use Non-instantiable util class whose constructor is private, and define all the constants as ‘public static final’
I have to extend the this constant util class. I can only do this when I change the constructor to protected.
Could somebody suggest a better way.
public class Constants {
private Constants () {} // Prevent instantiation
public static final String MyString = "MyString";
}
public class MyConstants extends Constants {
private MyConstants () {} // Compiler error : Implicit super constructor Constants() is not visible.
public static final String MySecondString = "MySecondString";
}
You are not typically supposed to extend these constant classes. Could you provide us with a more concrete example of what you’re trying to do?
Typically you’d want to group constants together when they are related, e.g., maths constants or configuration parameter names for a particular functional component.
If the constants are really related, is there anyway you could just add them to the original class? Alternatively, is there any reason you can’t create a separate class for your constants?