Call protected method from a subclass of another instance of different packages

孤者浪人 提交于 2019-11-29 05:07:52

You could access the protected methods either by subclassing and overriding; also when they are available in the same package. I will add some details. You can read details here.

The example that you have is on lines of the protected clone() method available in the Object class in java; you cannot directly call it on any object (although all object implicitly extend from the Object class).

Don't know the rationale, but JLS confirms this in 6.6.2. Details on protected Access (emphasis mine):

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

So:

package P2;
public class P2 {
    protected void foo() {}
}

.........

package P2A;    
class P2A extends P2.P2 {
    void bar(P2.P2 other) {
        this.foo(); // OK
        other.foo();  // ERROR
    }

    void bar2(P2A other) { 
        other.foo(); //OK
    }
}   

In P2A.bar a call to this.foo() is accessible because this is responsible for implementation of P2 but other.foo() is not accessible because other may not be a P2A. bar2 on the other hand has a P2A so it is all good.

Now, why all is OK if they are all the same package but not if they are different packages? What is the rationale? I don't know and would like to know.

Meta-Comment I have rolled back a recent update by another user as it substantially changes the answer and is probably more suitable as a top level answer itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!