Inheritance with local classes

46 Views Asked by At

So i was working with local classes this morning when I encountered a strange behaviour of inheritance regarding scopes.

public class Foo{
    public void printer(){
        class Hello extends Bar{
           private String str = "Hello";
        }

        class World extends Hello{
           private void print(){
              System.out.println(super.str);
           }
        }
    }
}

With class Bar looking like this:

public class Bar{
   protected String str = "FooBar";
}

So i expected an ouput like this:

FooBar

But ended up with:

Hello

Shouldn't the private prefix of the String declaration prevent the child class from accessing the variable?

However I procceded further and removed the String declaration and this time ended up with my previous expected ouput.

So why doesn't it always get the variable of class Bar when a variable of the same name is declared private in the direct parent class?

Thanks for any help in advance.

0

There are 0 best solutions below