【问题标题】:When referencing a private variable, do you need the this.variableName declaration? [closed]引用私有变量时,是否需要 this.variableName 声明? [关闭]
【发布时间】:2016-07-11 12:15:44
【问题描述】:
public class sample {
    private int x = 3;
    public sample() {}
    public sample(int num) {
        this();
        x = num;
    }

    public int getX() {
        // should I use return this.x; or just return x;? Does it matter which one?
    }
}

我使用了 return x;到目前为止,我的代码中的样式,我想知道是否使用 return this.x;提供任何好处,或者如果它纯粹是为了可读性/清晰。如果这看起来含糊不清或令人困惑,我深表歉意,我真的不知道该怎么说。

【问题讨论】:

  • 你为什么不试试呢?还有你为什么打电话给this();
  • 我在预设类中有一些我没有包含在代码 sn-p 中的东西,因为它并不真正相关。而且我一直只是按照 return x; 的方式进行操作,但注意到很多人使用 this.x 代替,想知道是否有任何好处。

标签: java variables constructor return private


【解决方案1】:

考虑setX(int x),为了消除参数x 和字段x 之间的歧义,您需要编写类似

public void setX(int x) {
    this.x = x;
}

否则(如果x 不是shadowed),则不需要指定this(它是隐式)。

public int getX() {
    return x; // <-- same as return this.x;
}

【讨论】:

  • 人们是否经常使用与私有变量同名的局部变量,还是通常会避免这种情况?
  • @JavaTheHutt 我会说变异器并不少见;但是,样式指南建议您在访问字段时始终使用this.x 也很常见。
【解决方案2】:

没有。你应该可以使用return x;。从技术上讲,您应该使用 this.x 的唯一原因是您的方法中有一个局部变量 x

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2011-04-04
    • 2018-12-29
    • 2012-04-09
    相关资源
    最近更新 更多