[英]Should I use static method or static fields
我想声明一些静态变量并在我的代码中大量使用它们,所以在这个例子中,如果我想更改电话号码,我将在一个地方更改它:
public class AppInformation{
static String phone_number="44444444";
}
所以现在我可以通过调用类来获取 phone_number : AppInformation.phone_number
;
另一种解决方案:
public class AppInformation {
public static String get_phone_number(){
return "44444444";
}
}
现在我可以调用该方法: AppInformation.get_phone_number
();
其实我更喜欢第二种方法,因为它是线程安全的!
这样对吗? 还有其他建议吗?
将其声明为public static final String PHONE_NUMBER = "44444444"
。 由于您只能读取此变量,因此它是线程安全的。
为什么我将它命名为PHONE_NUMBER
,而不是phoneNumber
(或打破我所知道的所有 Java 约定phone_number
),解释here 。
您可以将其声明为
static final String phone_number="44444444"; 并且不再担心线程安全:)
你的意思是你想要一个常量,在 Java 中,通常是这样表示的:
public class AppInformation
{
public static final String PHONE_NUMBER = "44444444";
}
请注意,在您的示例中,您错过了:
final
关键工作,这意味着可以在程序运行时修改该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.