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
?
I know when should normally I use this
, but this example is very different from normal usages.
Example:
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;
}
}
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.
Here's a description for each:
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