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
;
Another solution:
public class AppInformation {
public static String get_phone_number(){
return "44444444";
}
}
Now I could call the method: 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"
. 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 .
You can declare it as
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:
public class AppInformation
{
public static final String PHONE_NUMBER = "44444444";
}
Note, in your example you've missed:
final
keywork, which means the value could be modified when the program is running.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.