使用Java中的局部变量隐藏实例变量 [英] Shadowing instance variables with local variables in Java

查看:200
本文介绍了使用Java中的局部变量隐藏实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过如果另一个具有相同名称的变量在范围内更近,则变量会被遮蔽。我发现这个Point类有一个构造函数作为例子:

I have read that " a variable is shadowed if there is another variable with the same name that is closer in scope". I found this Point class with a constructor as an example:

public class Point {
    public int x = 0;
    public int y = 0;

    public Point(int x, int y) {
        x = x;
        y = y;
    }
}

然后我创建了一个Point类的对象CreateObjectDemo类低于
并打印变量x的值。

Then I created an object of the Point class in the CreateObjectDemo class below and printed the value of the variable x.

public class CreateObjectDemo {
    public static void main(String[] args) {

    Point originOne = new Point(23, 94);

    System.out.println(originOne.x);

    }

}

运行后编译器,它打印0.但为什么不打印23?我认为构造函数中的x = x就像23 = 23。我是否误解了阴影变量的定义?

After running the compiler, it prints 0. But why doesn't it print 23? I thought that "x = x" in the constructor would be like "23 = 23". Did I misunderstand the definition of shadowing variables?

推荐答案


我认为x = xin构造函数就像23 = 23。

I thought that "x = x" in the constructor would be like "23 = 23".

在构造函数中,简单名称的含义 x 总是只是参数。因此构造函数中的赋值 x = x 获取 x 参数的值并将其赋值给 x 参数。永远不会触及实例变量。 (目前还不清楚你的意思是 23 = 23; ,所以我不知道这是否准确。)基本上,这是一个无操作和一些IDE会给你一个关于它的警告。

Within the constructor, the meaning of the simple name x is always just the parameter. So the assignment x = x in the constructor takes the value of the x parameter and assigning it to the x parameter as well. The instance variable is never touched. (It's not clear what you mean by 23 = 23;, so I can't tell whether or not that's accurate.) Basically, this is a no-op and some IDEs will give you a warning about it.

要强制它复制到实例变量,你需要:

To force it to copy to the instance variable, you want:

this.x = x;

(同样适用于 y ,当然。)

(And likewise for y, of course.)

这篇关于使用Java中的局部变量隐藏实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆