我不明白一些关于公共静态字符串的事情。我有几个变量需要全局访问(我知道这不是真正的面向对象方法)。如果我从Globals类传递公共静态字符串字符串“引用”,则对SomeClass中的值所做的任何更改都不会更新该变量。
public class Globals{
public static String str;
}
public class SomeClass{
private String str;
public void setStr(String str){
this.str = str;
//If I change the value of str in this SomeClass, the value does not get
//updated for the public static String str in Globals class
}
//Here assign new value for str
}发布于 2012-03-12 23:44:47
您的作用域不明确。你的意思是:
public void setStr(String str){
this.str = str;
//If I change the value of str in this SomeClass, the value does not get
//updated for the public static String str in Globals class
Globals.str = this.str;
}或者这样:
public void setStr(String str){
this.str = str;
//If I change the value of str in this SomeClass, the value does not get
//updated for the public static String str in Globals class
this.str = Globals.str;
}希望这能有所帮助。
发布于 2012-03-12 23:42:38
这是因为您没有调用“全局”str变量,而是调用了类局部str变量。
如果没有关于您想要更改的str变量的额外信息,Java将使用具有给定名称的最严格范围的变量。就像您在构造函数中使用this.str来指示您想要SomeClass类的私有实例变量一样,您需要执行Globals.str来指示您想要用作全局变量的public static str变量。
此外,正如其他人所指出的那样,String在Java语言中是不可变的,所以当您为任何类型为String的变量赋值时,您真正要做的就是更改变量所引用的String。
发布于 2012-03-12 23:43:02
str类变量是为Globals类静态声明的,而不是为应用程序中的每个类声明的。Someclass中的str与Globals中的str没有关系-它们只是碰巧具有相同的标识符。
https://stackoverflow.com/questions/9670125
复制相似问题