Java: calling a protected method of a super class from a subclass - not visible?

I call the protected method of the super class from a subclass. Why is this method "invisible"?

I read some posts, such as this one , that seem to contradict the following:

Super class:

package com.first; public class Base { protected void sayHello() { System.out.println("hi!"); } } 

Subclass:

 package com.second; import com.first.Base; public class BaseChild extends Base { Base base = new Base(); @Override protected void sayHello() { super.sayHello(); //OK :) base.sayHello(); //Hmmm... "The method sayHello() from the type Base is not visible" ?!? } } 
+5
source share
3 answers

base is a variable that is not special: it is not part of the class hierarchy, and through it, secure access is not available. Although sayHello has access to protected base members, it only has access through inheritance (since it is not in the same package: the protected keyword allows access through both inheritance and package, see the table in this Oracle tutorial ) .

Access through this and super permitted as they are part of the inheritance hierarchy.

+9
source

This is the correct behavior. In fact, the Java Language Specification , section 6.6.2-1, has an example very similar to yours, with a comment that it should not compile.

Access to protected members is described in detail in Section 6.6.2.1:

6.6.2.1. Protected Member Access

Let C be the class in which the protected member is declared. Access is permitted only inside the body of subclass S C

In addition, if Id denotes an instance field or instance method, then:

If access is by the qualified name Q.Id , where Q is an expression, then access is allowed if and only if the type of the expression Q is S or a subclass of S

If access is through an access expression to the field E.Id , where E is the primary expression or the call expression of the method E.Id(. . .) , Where E is the primary expression, then access is allowed if and only if type E is equal to S or subclass S

This is the last paragraph that describes why access is denied. In your example, C has Base , S is BaseChild and E , the type of the Base variable is also Base . Since Base is neither BaseChild nor a subclass of BaseChild , access is denied.

+3
source

The keyboard is protected for visibility in one package. If the child class does not have the same package, the protected methods of the parent will not be visible to the child class.

-3
source

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


All Articles