简体   繁体   中英

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, and 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.

似乎是一个很好的候选人在我的财产文件中输入。

您可以使用抽象类作为该包中每个impl的基类。

You could make a special (static) class with just this variable. Later you can add other constants or whatever you need to that class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM