I have have a class A in Java and A has some protected methods, I then have a class B which extends from A so that B can override those protected methods. I then want the ability to have a class C that extends from class B but class C should not be able to call A‘s protected methods. Is there away to do that in Java? Do I just make the parent’s class’s method’s overriden and have them final? i.g.
public class A()
{
protected void somemethod();
protected int somevariable;
}
public class B() extends A
{
@Override
final protected void somemethod();
//How do I make some variable final or not accessible to my children?
}
public class C() extends B
{
//Now I cannot override somemethod! Is that right?
}
}
No, you cannot prevent a child class from calling a parent’s
protectedmethods. To achieve this, you would have to reduce the method’s visibility, which is not allowed. Making the methodfinalin your classBonly means it cannot be overriden in any subclasses.The fact that you want disallow calls to
protectedmethods for child classes appears to be a design problem to me. You might want to review how your whole class hierarchy and maybe better isolate the reponsibilites of your classes so that you don’t get into a situation where you have to prevent what would normally be allowed (callingprotectedmethods).