简体   繁体   中英

How to share class constants between classes?

I have 3 different classes that both use some constant values. Currently, I'm defining all of them for each of the class. How do I centralize them?

I tried to create a new static class with just the constants, and then use static import in my classes, but that didn't work. The class could not be imported successfully.

PS: I don't want to use enum and interface.

You cannot import classes from the default package (ie the /src directory). You need to include the package name in the import clause, even if both classes are in the same package.

For instance:

  • Class Main in /src
  • Class Constants in /src/utils

In class Main :

 import static utils.Constants.*;
 class Main {...}

In class Constants

 package utils.Constants;
 class Constants {...}

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