【问题标题】:Referring to instance variable with same name as a local variable in a constructor?在构造函数中引用与局部变量同名的实例变量?
【发布时间】:2015-12-09 23:05:57
【问题描述】:

这是一个主要是理论上的示例,但是在声明了局部变量“a”之后,如何在构造函数中引用实例变量“a”,而不是当前对象变量“this.a”?

public class Foobar {
    public int a = 0;

    public Foobar(int a) {
        this.a = a;
    }

    public Foobar(int b, int c) {
        a = b * c;
        int a = c;    //after this point, is there any way of refer to the instance variable a but not a in the current object (i.e. this.a)?

    }

    public int getA() {
        return this.a;
    }

    public static void main(String[] args) {
        Foobar foo = new Foobar(3);
        Foobar bar = new Foobar(3, 1);

        System.out.println(foo.getA());

        System.out.println(bar.getA());
    }

}

【问题讨论】:

  • 实例变量a和当前对象变量this.a是同一个变量。
  • 只有两个变量,this.aa。您已经描述了如何引用两者。
  • 但是当你声明一个局部变量“a”时,就不能再引用类变量“a”了,只能引用实例变量(使用“this.a”)。对吗?
  • 不,这是不对的。这甚至没有意义。这里没有“类变量a”,除非您的意思是“实例变量a”,因此是一回事。

标签: java oop syntax


【解决方案1】:

您的代码中没有类变量。

如果您想要一个类变量,请使用static int a。当然,您将无法使用 this.a 引用类变量:这仅适用于实例变量。

当然,你不能拥有同名的类变量和实例变量。

如果你用局部变量覆盖类变量,(坏主意 - 不要这样做 - 大多数 IDE 会警告你)然后可以使用 Foobar.a 引用类变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多