简体   繁体   中英

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????
  }
}


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 .

Your code is not in a subclass (you're in Test), and your code is not in the
same package (you're in Y). So the method is not visible. That's normal.

protected means you may call the method in any derived class. However, Test isn't derived from Transformation . genOutputSet is only visible inside Transformation and LookupTransformation . This doesn't tell anything about the visibility of methods when they are called on an object of the derived class.

The best possible answer I could give would be in the form of this picture that I used to learn it myself:

在此处输入图片说明

Protected methods work on subclasses( inherited classes in your case) that are in other packages aswell. You are however calling it from a different class(not subclass ). Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM