如何在方法内部更改公共变量的值?

huangapple go评论59阅读模式
英文:

How do we change the value of a public variable inside a method?

问题

这是一个示例:
如何在方法内部将变量 x 的值从 "a" 更改为 "b",以便在方法外部获得结果 "b"?

public class Main {

    String x = "a";
    public static void main(String[] args) {
        new Main();
    }

    public Main(){
        System.out.println(x); //"a"
        String x = "b";
        System.out.println(x); //"b"
        new Thread(new Runnable() {
            public void run() {
                String x = "c"; 
                System.out.println(x); //"c"
            }
        }).start();
        System.out.println(x); //"b"
    }

    public void method(){
        System.out.println(x); //"a"
    }
}
英文:

Here is an example:
How to change the value of x from "a" to "b" inside a method to get the result "b" outside of it?

public class Main {

    String x = "a";
    public static void main(String[] args) {
        new Main();
    }

    public Main(){
        System.out.println(x); //"a"
        String x = "b";
        System.out.println(x); //"b"
        new Thread(new Runnable() {
            public void run() {
                String x = "c"; 
                System.out.println(x); //"c"
            }
        }).start();
        System.out.println(x); //"b"
    }

    public void method(){
        System.out.println(x); //"a"
    }
}

答案1

得分: 7

String x = "b"; 是声明一个新的(局部)变量,它隐藏了相同名称的类变量。你所需要的是 x = "b";,不需要类型声明。

英文:

String x = "b"; is declaring a new (local) variable, which hides the class variable of the same name. What you need is x = "b";, without the type.

答案2

得分: 2

你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。以下是要翻译的内容:

通过执行String x = "b";,你正在声明一个新变量,但如果你想更新类变量的值,你需要指向特定的类变量,像这样:
你需要将String x = "b";替换为this.x = "b";

英文:

By doing String x = "b"; you are declaring a new variable but if you want to update the value of class variable you have to point on specific class variable like this:
you need to replace String x = "b"; with this.x = "b";

huangapple
  • 本文由 发表于 2020年8月8日 01:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63306831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定