Is the any difference in performance and/or any other benefits we can get when using final keyword with constant utility class. [ This class contains only static final fields and private constructor to avoid object creation]
public class ActionConstants {
private ActionConstants() // Prevents instantiation
{ }
public static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+";
public static final String VALIDPHONENUMBER = "\\d{10}";
...
...
}
Only diffrence is class is made final
public final class ActionConstants {
private ActionConstants() // Prevents instantiation
{ }
public static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+";
public static final String VALIDPHONENUMBER = "\\d{10}";
...
...
}
I like to know, is there any benefits there in using final and what is the correct way to define class for constants.
There is no benefit. It does not change anything regarding your static final
attributes.
When a class is made final, the compiler can take advantage of this for overridable methods (static methods cannot be overriden, at best, they hide those one in inherited classes).
Since the class is final, the compiler knows none of its method can be overriden. So, it can compute cases where polymorphism code does not need to be generated (i.e., the code finding the right 'version' of the overriding method according to the object instance at runtime). Hence, an optimization is possible.
If you want to make a class truly unique, you can use something like this:
public enum ActionConstants {
INSTANCE;
public static final int cte1 = 33;
public static final int cte2 = 34;
}
And if you are not interested in a class instance at all, just put all your constants in an interface.
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