我有一个常量字符串列表,我需要在我的Java程序中的不同时间显示.
在CI中可以在我的代码顶部定义这样的字符串:
#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"
Run Code Online (Sandbox Code Playgroud)
我想知道在Java中做这种事情的标准方法是什么?
der*_*ann 116
通常,您会将其定义为类的顶部:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Run Code Online (Sandbox Code Playgroud)
当然,根据您使用此常量的位置使用适当的成员可见性(public
/ private
/ protected
).
Ern*_*ill 12
它看起来像这样:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Run Code Online (Sandbox Code Playgroud)
如果常量只在一个类中使用,那么你需要制作它们private
而不是public
.
小智 5
您可以使用
public static final String HELLO = "hello";
Run Code Online (Sandbox Code Playgroud)
如果你有很多字符串常量,你可以使用外部属性文件/简单的“常量持有者”类
我们通常将常量声明为static
。原因是每次实例化类的对象时,Java 都会创建非静态变量的副本。
因此,如果我们创建常量,static
它就不会这样做并且会节省内存。
随着final
我们可以把这些变量不变。
因此,定义常量变量的最佳实践如下:
private static final String YOUR_CONSTANT = "Some Value";
Run Code Online (Sandbox Code Playgroud)
访问修饰符可以private/public
取决于业务逻辑。
归档时间: |
|
查看次数: |
146140 次 |
最近记录: |