I want a constant variable to be common to all classes in a package. Is there a way I can do this without making an interface just with the one definition in it, and making every class implement that?
To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
In Java, all constants have to reside in a type (class or interface). But you don't have to implement an interface to use a constant declared inside.
You can try by putting something like this in your package:
interface Constants {
static final String CONSTANT = "CONTANT";
}
and then, using it like this:
String myVar = Constants.CONSTANT;
This way, you still have your interface, but no classes implement it.
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