How can I have a constant variable common to all classes in a package?
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, a开发者_开发技巧nd making every class implement that?
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.
Generally applications have a "Constants" class or interface that holds all constants.
I generally to to group constants into logical classes. For instance if there can be two kinds of employees, regular and contract:
class EmployeeType
{
public static final String REGULAR = "regular";
public static final String CONTRACT = "contract";
}
and use it as EmployeeType.REGULAR
If the constants cannot be grouped this way, have a separate class/interface to hold these.
class Constants
{
public static final String APPLICATION_DOMAIN = 'domain';
}
You need not extend/implement this class interface to use the values. The constants will generally be declared public static final
, you can access them directly: Constants.APPLICATION_DOMAIN
Use a package private class:
class Constants{
public static final int MY_VALUE = 1234;
}
This can only be accessed by classes from the same package:
int val = Constants.MY_VALUE;
You can do this in various ways:
- One way (as mentioned here) is to create a Global constant interface and have a
public static final
attributes of each constants.` - Create properties file. By having a properties file, you'll have a Key value pair (separated by a
=
operator) each declared on a newline. Here's a tutorial on how to create and use properties file.
Seems like to be a good candidate for an entry in a property file to me.
You can use an abstract class to serve as the base class for each impls in that package.
You could make a special (static) class with just this variable. Later you can add other constants or whatever you need to that class.
精彩评论