首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java - public static String get "reference“

java - public static String get "reference“
EN

Stack Overflow用户
提问于 2012-03-12 23:40:29
回答 7查看 16.2K关注 0票数 0

我不明白一些关于公共静态字符串的事情。我有几个变量需要全局访问(我知道这不是真正的面向对象方法)。如果我从Globals类传递公共静态字符串字符串“引用”,则对SomeClass中的值所做的任何更改都不会更新该变量。

代码语言:javascript
复制
    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

    }
EN

回答 7

Stack Overflow用户

发布于 2012-03-12 23:44:47

您的作用域不明确。你的意思是:

代码语言:javascript
复制
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;
}

或者这样:

代码语言:javascript
复制
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;
}

希望这能有所帮助。

票数 4
EN

Stack Overflow用户

发布于 2012-03-12 23:42:38

这是因为您没有调用“全局”str变量,而是调用了类局部str变量。

如果没有关于您想要更改的str变量的额外信息,Java将使用具有给定名称的最严格范围的变量。就像您在构造函数中使用this.str来指示您想要SomeClass类的私有实例变量一样,您需要执行Globals.str来指示您想要用作全局变量的public static str变量。

此外,正如其他人所指出的那样,String在Java语言中是不可变的,所以当您为任何类型为String的变量赋值时,您真正要做的就是更改变量所引用的String

票数 3
EN

Stack Overflow用户

发布于 2012-03-12 23:43:02

str类变量是为Globals类静态声明的,而不是为应用程序中的每个类声明的。Someclass中的str与Globals中的str没有关系-它们只是碰巧具有相同的标识符。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9670125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档