Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a constant variable common to all classes in a package?

Tags:

java

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?

like image 325
oadams Avatar asked Oct 12 '10 10:10

oadams


People also ask

How do you make a variable constant in Java?

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.

How do you declare a variable to have a constant value?

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.


1 Answers

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.

like image 161
Vivien Barousse Avatar answered Sep 28 '22 11:09

Vivien Barousse