Unable to access protected method from child class

So we have

public abstract class A{ protected abstract String f(); } public class B extends A{ protected String f(){...} } public class C extends A{ protected String f(){ A b = (A) Class.forName("B", true, getClass().getClassLoader()).newInstance(); return bf(); } 

This does not allow me to access bf() , saying that bf() is in a protected area, however f was protected by A , and since C extends A , it must also access f() .

+5
source share
2 answers

A protected modifier indicates that access to an element can only be accessed in its own package (as is the case with the private package) and, in addition, by subclassing its class in another package.

If you want to access Bf (), you must have class C defined in the same package as B.

+3
source

No, because the compiler does not know if b instance of b , C or other external classes.

Suppose there is a class D such that D extends A in another package. If b is an instance of D (the compiler does not know) bf() should be denied if access is protected (classes in other packages cannot access them).

0
source

All Articles