I noticed a peice of code I was looking at, that the author used:
class MainClass
{
protected int someVar = 1;
private SomeClass someClass = new SomeClass(this, new SomeActionListener() {
protected void onAction() {
MainClass.this.someVar ++;
}
});
public MainClass()
{
}
}
Note how he used MainClass.this to get the proper context of ‘this’ to change the scope back to MainClass. I’ve never seen this done before – can someone explain?
The anonymous instance is bound to the scope of the instance in which it is created. Therefore it can also access everything within.
thiswould refer to the anonymous instance andMainClass.thisto the instance in which the anonymous instance was created. If for example thesomeClassmember would have been declared asstatic, you could not have usedMainClass.this.