问题
Why this code work:
class Parent {
private void methodA(String a){
System.out.println(a);
}
class Inner {
void test(int a){
methodA("1");
}
}
}
But This code not work(I just add method to inner class with same name and another signature):
class Parent {
private void methodA(String a){
System.out.println(a);
}
class Inner {
private void methodA(int a){
System.out.println(a);
}
void test(int a){
methodA("1");
}
}
}
I do not ask how to make it work. I want to mean why the second option doesn't work? I want an explanation, not a solution.
回答1:
It doesn't work because you changed the meaning of the name methodA
.
Because a method called methodA
is present in the body of the class in which you are invoking a method called methodA
, the compiler doesn't look at the surrounding scopes.
The specific bit of the language spec is Sec 15.12.1 (emphasis mine):
If the form is MethodName, that is, just an Identifier, then:
...
If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.
You can invoke the parent method still via:
Parent.this.methodA("1");
回答2:
When compiler starts scanning the code it first look for the nearest scope availability. If it doesn't find it then only it go for a higher scope.
In your case, compiler will find method methodA
in Inner
class. So it will not look for the method available in Parent
class.
Still if you want to force compiler to look for Parent
class method than you have to use below code.
Parent.this.methodA("1");
来源:https://stackoverflow.com/questions/53496685/java-compiler-prohibit-the-creation-in-the-inner-class-method-with-same-name-as