Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

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

I want to invoke a protected method of another instance from within a subclass of the class providing this protected method. See the following example:

public class Nano {

    protected void computeSize() {
    }

}

public class NanoContainer extends Nano {

    protected ArrayList<Nano> children;

}

public class SomeOtherNode extends NanoContainer {

    // {Nano} Overrides

    protected void computeSize() {
        for (Nano child: children) {
            child.computeSize();            // << computeSize() has protected access in nanolay.Nano
        }
    }

}

javac tells me that computeSize() has protected access in Nano. I can't see the reason for this (I thought I was already doing this in some other code). I'd like to keep this method being protected, what can I do?

javac version "1.7.0_09"

Edit

I wanted to provide a stripped down version, but I didn't think about the fact, that the classes lie in different packages.

nanolay.Node
nanolay.NanoContainer
nanogui.SomeOtherNode
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...