简体   繁体   English

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

[英]Should I use static method or static fields

I want to declare some static variables and use them a lot in my code, so in this example if I want to change the phone number I will change it in one place:我想声明一些静态变量并在我的代码中大量使用它们,所以在这个例子中,如果我想更改电话号码,我将在一个地方更改它:

public class AppInformation{
    static String phone_number="44444444";
}

So now I could get the phone_number by calling the class : AppInformation.phone_number ;所以现在我可以通过调用类来获取 phone_number : AppInformation.phone_number

Another solution:另一种解决方案:

public class AppInformation {

    public static String get_phone_number(){
        return "44444444";
    } 
}

Now I could call the method: AppInformation.get_phone_number ();现在我可以调用该方法: AppInformation.get_phone_number ();

Actually I prefer the second method because it is thread safe!其实我更喜欢第二种方法,因为它是线程安全的!

Is this correct?这样对吗? Are there any other suggestions?还有其他建议吗?

Declare it as public static final String PHONE_NUMBER = "44444444" .将其声明为public static final String PHONE_NUMBER = "44444444" Since you can only read this variable, it is thread-safe.由于您只能读取此变量,因此它是线程安全的。

Why I named it PHONE_NUMBER , not phoneNumber (or breaking all known to me Java conventions phone_number ), is explained here .为什么我将它命名为PHONE_NUMBER ,而不是phoneNumber (或打破我所知道的所有 Java 约定phone_number ),解释here

You can declare it as您可以将其声明为

static final String phone_number="44444444"; static final String phone_number="44444444"; And do not worry about threadsafe anymore :)并且不再担心线程安全:)

What you are saying is that you want a constant, which in Java, is commonly expressed like this:你的意思是你想要一个常量,在 Java 中,通常是这样表示的:

public class AppInformation
{
  public static final String PHONE_NUMBER = "44444444";
}

Note, in your example you've missed:请注意,在您的示例中,您错过了:

  • the access modifier , which in the case of a class means the value would be package private. 访问修饰符,在类的情况下意味着该值将是包私有的。
  • the final keywork, which means the value could be modified when the program is running. final关键工作,这意味着可以在程序运行时修改该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM