Reputation: 525
I've encountered an interesting behavior in Java regarding forward references in instance initializer blocks. When I try to access an instance variable directly, I get a forward reference error. However, when I use the this keyword to access the same variable, the error disappears. I'm trying to understand why this happens.
class Thing {
// Instance Initializer
{
// firstString = secondString; // Compilation error: forward reference
firstString = this.secondString; // No error, compiles successfully
}
// Instance variables
String firstString;
String secondString;
public String toString() {
return firstString + secondString;
}
}
public class ForwardReference {
public static void main(String[] args) {
Thing one = new Thing();
System.out.println(one);
}
}
firstString = secondString;
cause a forward reference error, but firstString = this.secondString;
doesn't?this.secondString
when it's accessed in the initializer block, given that secondString
hasn't been explicitly initialized yet?firstString = secondString;
and firstString = this.secondString;
would either cause errors or be allowed.firstString = this.secondString;
is allowed and compiles without errors.I understand that instance variables are initialized to their default values (null for reference types) before any initializer blocks are executed. However, I'm curious about why the this keyword seems to change how the compiler treats these references.
As fas as I research: initialization occurs in these steps:
Upvotes: 4
Views: 44