Why subclass in another package cannot access a protected method?

后端 未结 7 2210
一向
一向 2020-11-30 05:07

I have two classes in two different packages:

package package1;

public class Class1 {
    public void tryMePublic() {
    }

    protected void tryMeProtect         


        
7条回答
  •  执念已碎
    2020-11-30 05:35

    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.

提交回复
热议问题