I know how to get this code to work, but I’m curious why the compiler is not able to figure out that the call is to the outer class method:
public class Example {
public void doSomething(int a, int b)
{
}
public class Request
{
public int a;
public int b;
public void doSomething()
{
doSomething(a,b); // Error. Fix: Example.this.doSomething(a,b);
}
}
}
Is there a deeper design reason for this than protecting coders from making mistakes?
By the language definition, the outer-class method is not visible in the inner class because it is shadowed.
Shadowing is based on name rather than signature. This is a good thing.
Consider the alternative. You could hide a subset of method overloads. Someone else could try to change the arguments in a call, to call one of the other overloaded methods. Simply changing the arguments could cause the recipient object to change. This would be surprising, and could cost time to debug.
From the Java Language Specification, 6.3.1: