Bi Act
Bi Act

Reputation: 434

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


Upvotes: 4

Views: 12267

Answers (4)

Eran
Eran

Reputation: 393831

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.

Upvotes: 6

Juxhin
Juxhin

Reputation: 5600

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

enter image description here

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!

Upvotes: 1

pascalhein
pascalhein

Reputation: 5846

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.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39457

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.

Upvotes: 3

Related Questions