| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Why it doesn't compile when an inner class has a method of the same name (but different signature) as that of its enclosing class?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Why it doesn't compile when an inner class has a method of the same name (but different signature) as that of its enclosing class?The compiling the following code will generate an compilation error:
public class Program {
class Inner {
void method(int i) {};
void doSomething() {
method(); //compiler error
}
}
void method() {}
}
Determining the method that will be invoked by a method invocation expression involves several steps:
In our case, the Identifier is method method and the type T is the inner class Program.Inner. All inherited methods from superclass are included in such matching list but methods from enclosing classes are not in the matching list. The list consists only void method(int i) which is defined in Inner class. According to 15.12.2 Compile-Time Step 2: Determine Method Signature, "The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments". In our case, the compiler realizes that the parameters don't match any methods provided by the first step and generates an error. The list consists only void method(int i) which is defined in Inner class and that does not match the required signature. How can I call void method() in the enclosing class? Every inner class must be associated with an instance of its enclosing class. In fact, every inner class has an implicit reference to that enclosing class. That implicit reference takes the form "EnclosingClass.this". In our case, we can use Program.this.method() to fix this problem:
public class Program {
static String str = "Hello from Program";
class Inner {
static String str = "Hello from Inner";
void method(int i) {};
void doSomething() {
System.out.println(Program.this.str); //Hello from Program
Program.this.method();
}
}
void method() {}
}
|