When does Java compiler automatically append this keyword in my class?
public class Alphabets
{
int a;
public void gen_1(int b){
a=b; //equivalent to this.a=b
gen_2(); //is this equivalent to Alphabets.gen_2() or this.gen_2?
public static void gen_2()
{}
CodePudding user response:
Whenever it wouldn't compile without it. It's not so much that javac 'adds the this. for you' - it's that javac will interpret a certain expression in a certain way.
In your example, a is equivalent to this.a not because "java will add the this." - it's equivalent because just a and this.a refer to the same thing: The only a that is in scope. Java will look at the closest matching name in scope. Example:
int a = 2;
void example() {
int a = 5;
{
int b = 10;
{
System.out.println(a);
}
}
}
2 scopes up, there's an a (a local var, being assigned the value of 5). It's closer than the field. Not in literal 'how many lines in the source file is it removed from this line', but in the: "Start looking in the nearest set of {}, if you can't find it there, look in the next set, and just keep going until you find it" way.
For that reason, gen_2() does not 'generate this.', because that's not how you should think about it. It looks for a method named gen_2 (why a method? Because there are parentheses hanging off of the end of it), and finds one in the Alphabets {} scope. That's the one it'll invoke. It'll do this in a static fashion, because the method is static. Not because java 'generates Alphabets.'.
CodePudding user response:
Any programming language has to have rules about how the compiler determines the meaning of a name. Java is no exception; its rules are in Chapter 6 of the Java Language Specification.
The full set of rules is quite elaborate, but the simplified answer to your question is: if there's an unqualified name that identifies something that is a member of the current object, and it is not obscured by a more local declaration of the same name, then the name means the member of the current object, i.e., 'this' is implied.
