Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force abstract methods to be protected when someone overrides them?

In my abstract class, I have something like this:

public Object methodIWantToExpose(){   // ...    methodIDontWantExposed()   // ... }  protected abstract void methodIDontWantExposed(); 

The thing is, I want to force the person that extends methodIDontWantExposed() to make it protected, because I don't want the extending class to have both methodIDontWantExposed and methodIWantToExpose exposed.

Is there a way to do this (or a different approach which might avoid my problem)?

like image 493
justsomeusername Avatar asked Feb 23 '15 10:02

justsomeusername


People also ask

Can abstract method be protected?

Declaring an abstract method protectedYes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.

Can we override protected abstract method in Java?

Yes, the protected method of a superclass can be overridden by a subclass.

Can you override an abstract method?

A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Do you have to override abstract class methods?

Overriding Abstract Classes in Java In Java, it is compulsory to override abstract methods of the parent class in its child class because the derived class extends the abstract methods of the base class. If we do not override the abstract methods in the subclasses then there will be a compilation error.


1 Answers

No. A subclass can always make a method more public.

Even if they couldn't do this with the method you have in your class, they could always write:

public void callsMethodIDontWantExposed() {     methodIDontWantExposed(); } 

... so you'd be in the same situation.

like image 161
Jon Skeet Avatar answered Sep 28 '22 17:09

Jon Skeet