Suppose you need to define a class which all it does is hold constants.
public static final String SOME_CONST = "SOME_VALUE";
What is the preferred way of doing this?
Which one should I use and why?
Enums - I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way.
Interface - I'm not going to set any class as one that implements the interface. Just want to use the interface to call constants like so: ISomeInterface.SOME_CONST
.
To turn an ordinary variable into a constant, you have to use the keyword "final." As a rule, we write constants in capital letters to differentiate them from ordinary variables. If you try to change the constant in the program, javac (the Java Compiler) sends an error message.
Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Use a final class. for simplicity you may then use a static import to reuse your values in another class
public final class MyValues { public static final String VALUE1 = "foo"; public static final String VALUE2 = "bar"; }
in another class :
import static MyValues.* //... if(variable.equals(VALUE1)){ //... }
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