在Java中定义常量字符串?
我有一个常量字符串列表,我需要在Java程序的不同时间显示这些字符串。
在C中,我可以在代码顶部定义如下字符串:
#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"
我想知道在Java中做这种事情的标准方法是什么?
我有一个常量字符串列表,我需要在Java程序的不同时间显示这些字符串。
在C中,我可以在代码顶部定义如下字符串:
#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"
我想知道在Java中做这种事情的标准方法是什么?
通常,您会在类的顶部定义此内容:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
当然,请根据使用此常量的位置使用适当的成员可见性 (//)。public
private
protected
它看起来像这样:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
如果这些常量仅用于单个类,则需要使它们代替 。private
public