Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the protected method not visible?

Tags:

java

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


like image 434
Bi Act Avatar asked Oct 23 '25 19:10

Bi Act


2 Answers

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.

like image 115
Eran Avatar answered Oct 26 '25 10:10

Eran


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.

like image 39
peter.petrov Avatar answered Oct 26 '25 08:10

peter.petrov