Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access protected method from child class [duplicate]

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 b.f();
}

This doesn't allow me to access b.f(), saying that B.f() is in the protected scope, however f was protected by A, and since C extends A, it should also get access to f().

like image 688
f.khantsis Avatar asked Oct 20 '22 07:10

f.khantsis


1 Answers

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

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

like image 181
Alex Objelean Avatar answered Oct 21 '22 23:10

Alex Objelean