当我使用this关键字访问类中的非静态变量时,Java不会给出任何错误。但是当我不使用它时,Java会给出一个错误。为什么要使用this?
this
我知道什么时候应该正常使用this,但是这个示例与正常用法大不相同。
例:
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 }
首先声明变量,然后赋值。该类与此相同:
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是,在创建对象时尚未定义,但是对象本身(即this)及其所有成员变量都存在。
int a = b;
b
这是每个的说明:
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