Why subclass in another package cannot access a protected method?

后端 未结 7 2149
一向
一向 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:54

    First of all, you need to understand two things:

    1) The protected member functions of a class 'X' in package 'Y' can be accessed by the subclass i.e. a class that extends it (even if the subclass is in the package other than 'Y'). That is why,

    tryMeProtected(); // Showed no error because this was called by class 2 that is the subclass.
    

    2) A protected member function of a class 'X' in package 'Y' cannot be accessed by itself if it is in other packages.

    [ A simple analogy: A bird that has its eggs kept in a nest 1 has flown to a nest 2. From the nest 2, it cannot access its egg kept in nest 1.] Similarly, a class cannot access its member function (unless public declared.) if it is in the other package.

    That is why :

    c.tryMeProtected();  // Showed error because this was called by class 1 reference.
                         //  You can also think of it as class 1 cannot inherit itself.
    
    0 讨论(0)
提交回复
热议问题