Why is the protected method not displayed?

Java experts, I sincerely appreciate any ideas!

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 a subclass from a class outside the package and call the protected method on the instance of the subclass, Eclipse complains that the protected method is not displayed.

I thought that protected methods would be visible to all children β€” in or out of the package β€” until the class’s visibility limits it β€” in this case, both the parent and child classes are publicly available. 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???? } } 


+2
source share
4 answers

protected genOutputSet can be called by classes that inherit from the class where it was declared, or classes that belong to the same package. This means that you can call it from LookupTransformation .

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

See further explanation here .

+3
source

Your code is not in a subclass (you are in Test), and your code is not in the same package directory (you are in Y). Therefore, the method is not displayed. This is normal.

+1
source

protected means that you can call a method in any derived class. However, Test not inferred from Transformation . genOutputSet is only displayed inside Transformation and LookupTransformation . This says nothing about the visibility of methods when they are called on an object of a derived class.

+1
source

The best answer I could give would be in the form of this picture, which I myself studied:

enter image description here

Protected work on subclasses ( inherited classes in your case), which are also in other packages . However, you are calling it from another class (not subclass ). Hope this helps!

+1
source

Source: https://habr.com/ru/post/1245675/


All Articles