我应该使用静态方法还是静态字段

use*_*596 2 java static multithreading

我想声明一些静态变量并在我的代码中使用它们,所以在这个例子中,如果我想更改电话号码,我会在一个地方更改它:

public class AppInformation{
    static String phone_number="44444444";
}
Run Code Online (Sandbox Code Playgroud)

所以现在我可以通过调用类来获取phone_number : AppInformation.phone_number;

另一种方案:

public class AppInformation {

    public static String get_phone_number(){
        return "44444444";
    } 
}
Run Code Online (Sandbox Code Playgroud)

现在我可以调用方法:( AppInformation.get_phone_number);

实际上我更喜欢第二种方法,因为它是线程安全的!

它是否正确?还有其他建议吗?

Ada*_*zyk 5

声明为public static final String PHONE_NUMBER = "44444444".由于您只能读取此变量,因此它是线程安全的.

在这里解释为什么我命名它PHONE_NUMBER,而不是phoneNumber(或打破我所知的所有Java约定phone_number).