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 mus
For any class in Java this is a default reference variable (when no specific reference is given) that either user can give or the compiler will provide inside a non-static block. For example
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;
}
}
You said that int a = b; // gives error. why ? gives compile time error because b is declared after a which is an Illegal Forward Reference in Java and considered as a compile-time error.
But in the case of methods Forward Reference becomes legal
int a = test();
int b;
int test() {
return 0;
}
But in my code, the constructor with the argument is declared before both a & b, but not giving any compile-time error, because System.out.println(b); will be replaced by System.out.println(this.b); by the compiler.
The keyword this simply means current class reference or the reference on which the method, constructor or the attribute is accessed.
A a1 = new A(); // Here this is nothing but a1
a1.test(); // Here this is again a1
When we say a = this.b; it is specifying that b is a current class attribute, but when we say a = b; since it is not inside a non-static block this won't be present and will look for an attribute declared previously which is not present.