0

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.

L.Spillner
  • 1,772
  • 10
  • 19
  • You should show your main method for how you ran this – OneCricketeer Feb 06 '18 at 08:08
  • By calling this line: `System.out.println(super.str);` You're actually calling super class of World, which is the Hello class. – sovas Feb 06 '18 at 08:08
  • @sovas I think that was understood already. The expected output was that of the `Bar` class – OneCricketeer Feb 06 '18 at 08:09
  • *Within a class, a field that has the same name as a field in the superclass hides the superclass's field*... https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html – OneCricketeer Feb 06 '18 at 08:11
  • @cricket_007 Thanks, I knew this part of the tutorial. I was just kind of confused why the ´private´ declaration doesn't bypass this rule. But the Post shmosel linked was more or less the explanation i searched for but didn't found. :) – L.Spillner Feb 06 '18 at 08:17
  • The `private` doesn't stop the fact that you are shadowing the field. If you want to override the value, you'd use methods. – OneCricketeer Feb 06 '18 at 08:20

0 Answers0