0

I'm puzzled and a little bit wasted by the next snippet. I guess it is all because of static inner class and scope of the function of class A1 which is called.

If you have a explanation-in-details, please share it!

public class Main {
    static class A1 {
        private void f() { System.out.println("A1");}
    }

    static class A2 extends A1 {
        public void f() {System.out.println("A2");}
    }

    static class A3 extends A2 {
        public void f() {System.out.println("A3");}
    }

    public static void main(String[] args) {
        A1 a1 = new A1();
        a1.f();
        a1 = new A2();
        a1.f();
        a1 = new A3();
        a1.f();
    }
}

Expected:

A1
A2
A3

Actual:

A1
A1
A1

1 Answers1

4

The method f() in A1 is marked private. This means that it is not inherited by A2 or A3. This means that polymorphism will not find the overriding methods f() in A2 or A3. However, because A1 is a nested class, the enclosing Main class still has access to it, so it compiles. The result is that A1 is printed 3 times.

You could see the error if you attempted to place an @Override annotation on f() in A2. If you change f() to public, protected, or no access modifier ("package access") in A1, then f() would get inherited as you expect, so that the output would be as you expect, with A1, A2, and A3 being outputted.

rgettman
  • 176,041
  • 30
  • 275
  • 357