Search code examples
javainheritancejavacinner-classes

Java compiler prohibit the creation in the inner class method with same name as in the outer class if the signatures are different


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.


Solution

  • 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");