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

I want the constant variable to be common to all classes in the package. Is there a way I can do this without creating an interface with only one definition in it and making each class implemented?

+6
java
source share
7 answers

In Java, all constants must be in a type (class or interface). But you do not need to implement an interface to use the constant declared inside.

You can try by posting something like this in your package:

interface Constants { static final String CONSTANT = "CONTANT"; } 

and then using it as follows:

 String myVar = Constants.CONSTANT; 

Thus, you still have your own interface, but not one of the classes implements it.

+8
source share

Typically, applications have a class or "Constants" interface that contains all the constants.

I usually group constants into logical classes. For example, if there can be two types of employees, regular and contractual:

 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 for storing them.

 class Constants { public static final String APPLICATION_DOMAIN = 'domain'; } 

You do not need to extend / implement this class interface in order to use the values. Constants are usually declared public static final , you can access them directly: Constants.APPLICATION_DOMAIN

+5
source share

Using the private package class:

 class Constants{ public static final int MY_VALUE = 1234; } 

Access to these resources can only get a class from one package:

 int val = Constants.MY_VALUE; 
+2
source share

You can do this in various ways:

  • One way (as already mentioned here) is to create a global persistent interface and have public static final attributes for each constant.
  • Create a properties file. Having a properties file, you will have a pair of key values ​​(separated by the = operator), each of which is declared in a new line. Here's a tutorial on how to create and use a properties file.
+1
source share

This seems to be a good candidate for writing to the properties file.

0
source share

You can use an abstract class to serve as a base class for each of them in this package.

0
source share

You can create a special (static) class with this variable only. Later you can add other constants or everything you need for this class.

0
source share