Why subclass in another package cannot access a protected method?

user2986848 picture user2986848 · Nov 13, 2013 · Viewed 31.1k times · Source

I have two classes in two different packages:

package package1;

public class Class1 {
    public void tryMePublic() {
    }

    protected void tryMeProtected() {
    }
}


package package2;

import package1.Class1;

public class Class2 extends Class1 {
    doNow() {
        Class1 c = new Class1();
        c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
        tryMeProtected();  // No error
    }    
}

I can understand why there is no error in calling tryMeProtected() since Class2 sees this method as it inherits from Class1.

But why isn't it possible for an object of Class2 to access this method on an object of Class1 using c.tryMeProtected(); ?

Answer

Ankur Shanbhag picture Ankur Shanbhag · Nov 13, 2013

Protected methods can only be accessible through inheritance in subclasses outside the package. And hence the second approach tryMeProtected(); works.

The code below wont compile because we are not calling the inherited version of protected method.

 Class1 c = new Class1();
 c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1

Follow this stackoverflow link for more explaination.