-1

Assumed, we have given the two classes:

package inheritance1;

public class Foo1 {

    protected void sayWhoYouAre() {
        System.out.println("I am Foo1");
    }
}

and

package inheritance2;

import inheritance1.Foo1;

public class Foo2 extends Foo1 {

    public Foo2() {
        // why does this not work?
        // new Foo1().sayWhoYouAre();
        // ---> Error: "The method sayWhoYouAre() from the type Foo1 is not
        // visible"
    }

    @Override
    protected void sayWhoYouAre() {
        System.out.println("I am Foo2");
    }

    public static void main(String[] args) {
        // why does this not work?
        // new Foo1().sayWhoYouAre();
        // ---> Error: "The method sayWhoYouAre() from the type Foo1 is not
        // visible"
    }
}

Why is the sayWhoYourAre()-method visible in the class definition so I can override it (@Override), but when I try to invoke it by new Foo1().sayWhoYouAre() the compiler says, that this method is not visible?

Thanks for your help! :)

mrbela
  • 4,477
  • 9
  • 44
  • 79
  • protected means the method is only visible for classes the same package or subclasses of those. In which context do you call `new Foo1().sayWhoYouAre() `? – Herr Derb Apr 07 '16 at 12:57
  • Isn't the constructor part of the subclass and so the protected method should be visible?! That I can't invoke it out of the main method, I've understood now! – mrbela Apr 07 '16 at 13:07
  • Yes you can invoke it from its constructor, but your not doing that here. – Herr Derb Apr 07 '16 at 13:38

1 Answers1

0

protected means that the method is visible in:

  • the same package of the class on which it is defined
  • any class that extends the class in which is defined. This covers the case why you can override it in Foo2

The main method however is static and therefore not part of the object scope of the class, meaning that it lies not within the inheritance hierarchy. For that reason sayWhoYouAre on Foo1 is not visible.

See also the JLS

hotzst
  • 7,238
  • 9
  • 41
  • 64