Search code examples
javavisibilityprotected

Java: calling a super class' protected method from a subclass - not visible?


I am calling a super class' protected method from a subclass. Why is this method "not visible"?

I've been reading some posts such as this one, that seem to contradict the following:

Super class:

package com.first;

public class Base
{
    protected void sayHello()
    {
        System.out.println("hi!");
    }
}

Subclass:

package com.second;

import com.first.Base;

public class BaseChild extends Base
{
    Base base = new Base();

    @Override
    protected void sayHello()
    {
        super.sayHello(); //OK :)
        base.sayHello(); //Hmmm... "The method sayHello() from the type Base is not visible" ?!?
    }   
}

Solution

  • base is a variable that is not special in any way: it's not part of a class hierarchy and protected access is not available through it. Even though sayHello has access to protected members of Base, it has that access only through inheritance (since it's not in the same package: the protected keyword allows access via both inheritance and package, see the table in this Oracle tutorial).

    Access through this and super is allowed because those are part of the inheritance hierarchy.