Home >Java >javaTutorial >Why Can't a Subclass in a Different Package Access a Protected Member of its Superclass in Java?
Navigating Java's Protected Access Modifiers
Problem:
Consider two classes, A in package1 and C in package2, where C extends A. Class A defines an instance variable protectedInt declared with the protected modifier. However, Eclipse reports an error when accessing this protectedInt from class C. This appears to contradict the documentation's definition of protected, which permits access within subclasses from other packages.
Answer:
The misunderstanding arises from the specific context in which protected access is granted. The JLS (Section 6.6.2) clarifies that protected members can indeed be accessed from subclasses in other packages, but only for instances of the subclass or instances of subclasses of the subclass.
Specifically, protected members can only be accessed via a field access expression (e.g., E.Id) or method invocation expression (e.g., E.Id(. . .)) if the type of E is the subclass itself (i.e., S) or a subclass of S.
In the given scenario, the code that attempts to access a.protectedInt is using an instance of A as the expression E. Since A is not a subclass of C, this access is not permitted according to the JLS rule.
Therefore, the protected modifier grants access to protected members within subclasses, but only for instances of the subclass or its subclasses.
The above is the detailed content of Why Can't a Subclass in a Different Package Access a Protected Member of its Superclass in Java?. For more information, please follow other related articles on the PHP Chinese website!