【发布时间】: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.a和a。您已经描述了如何引用两者。 -
但是当你声明一个局部变量“a”时,就不能再引用类变量“a”了,只能引用实例变量(使用“this.a”)。对吗?
-
不,这是不对的。这甚至没有意义。这里没有“类变量
a”,除非您的意思是“实例变量a”,因此是一回事。