Bi Act Bi Act - 1 month ago 30
Java Question

Why is the protected method not visible?

Java experts, I would sincerely appreciate any insights!

I have an abstract class in a package with a protected method. I also have a subclass of this class in the same package. Now, when I try to instantiate the subclass from a class outside the package, and invoke the protected method on the subclass' instance, Eclipse is complaining the protected method is not visible.

I thought, protected methods will be visible to all children - in or out of the package - as long as the class visibility does not restrict it - in this case, both the parent and the child class are public. What am I missing? Thanks in advance!

package X;
public abstract class Transformation {
protected OutputSet genOutputSet (List list) {
..
}
}





package X;
public class LookupTransformation extends Transformation {
}





package Y;
import X.*;
public class Test {
public static void main(String[] args) {
List<field> fld_list = new ArrayList();
..
LookupTransformation lkpCDC = new LookupTransformation();
OutputSet o = lkpCDC.genOutputSet(fld_list); // Eclipse errors out here saying genOutputSet from the Type Transformation is not visible. WWWWWWWWHHHHHAAAATTTTTT????
}
}




Answer

protected access means genOutputSet can be called by classes inheriting from the class where it's declared or by classes belonging to the same package. This means you can call it from within LookupTransformation.

However, you are trying to call it from an unrelated class - Test - located in a different package, which requires public access.

See additional explanation here.