Search code examples
javasubclasspackageprotectedaccess-modifiers

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

Solution

  • 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).