为什么我必须使用“ this”关键字以供参考? [英] Why must I use the "this" keyword for forward references?
问题描述
当我使用 this
关键字访问类中的非静态变量时,Java不会给出任何错误。但是当我不使用它时,Java会报错。为什么我必须使用 this
?
When I use the this
keyword for accessing a non-static variable in a class, Java doesn't give any error. But when I don't use it, Java gives an error. Why must I use this
?
我知道什么时候通常应该使用 this
,但此示例与正常用法有很大不同。
I know when should normally I use this
, but this example is very different from normal usages.
示例:
class Foo {
// int a = b; // gives error. why ?
int a = this.b; // no error. why ?
int b;
int c = b;
int var1 = this.var2; // very interesting
int var2 = this.var1; // very interesting
}
推荐答案
变量是首先声明,然后分配。该类与此相同:
Variables are declared first and then assigned. That class is the same as this:
class Foo {
int a;
int b;
int c = b;
int var1;
int var2;
public Foo() {
a = b;
var1 = var2;
var2 = var1;
}
}
不能执行的原因 int a = b;
是因为在创建对象时尚未定义 b
,而是对象本身(即这个
)及其所有成员变量都存在。
The reason you can't do int a = b;
is because b
is not yet defined at the time the object is created, but the object itself (i.e. this
) exists with all of its member variables.
下面是每个描述:
int a = b; // Error: b has not been defined yet
int a = this.b; // No error: 'this' has been defined ('this' is always defined in a class)
int b;
int c = b; // No error: b has been defined on the line before
这篇关于为什么我必须使用“ this”关键字以供参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!