对于 Javathis中的任何类,用户可以提供默认引用变量(当没有给出特定引用时),或者编译器将在非静态块中提供该变量。例如
public class ThisKeywordForwardReference {
public ThisKeywordForwardReference() {
super();
System.out.println(b);
}
int a;
int b;
public ThisKeywordForwardReference(int a, int b) {
super();
this.a = a;
this.b = b;
}
}
您说这int a = b; // gives error. why ?会产生编译时错误,因为在 Javab中声明之后a是一个Illegal Forward Reference并被视为编译时错误。
但在methods Forward Reference变得合法的情况下
int a = test();
int b;
int test() {
return 0;
}
但是在我的代码中,带有参数的构造函数在a&之前声明b,但没有给出任何编译时错误,因为System.out.println(b);将被System.out.println(this.b);编译器替换。
关键字this仅表示当前类引用或访问方法、构造函数或属性的引用。
A a1 = new A(); // Here this is nothing but a1
a1.test(); // Here this is again a1
当我们说它a = this.b;指定这b是一个当前类属性时,但是当我们说a = b;因为它不在非静态块内this时,它将不存在,并且会查找先前声明的不存在的属性。