简体   繁体   中英

Use static properties for constants with java

In my java program I use a Constants.java class. In this class I created about 50 Strings properties in this way

public static final String startError = "The program could not be started, please ......";

    public static final String logPath="/Users/hgvu/";

In my program I use this class in this way for example

System.out.println(Constants.startError);

I am new in the domain, do you think it's a good idea to make fields in the Constants class static ?

在我看来,常量不应该变化 - 因此它们应该始终是静态的......这也意味着您可以访问常量变量值而无需启动 Constants.java 类

Make your class final, like public final class Constants . And Java doesn't let you create top-level static classes, I think you meant making fields static when you asked "do you think it's a good idea to make the Constants class static". The answer is yes, it is the best way to go about it.

you wont be able to define a Static class in java unless it is nested , but if you want the constants to be shared across, then making it a nested class does not make any buyout.

But you can make your class final and have private constructor would be a good choice if you want this class to only contain your 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