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

access-modifiers, java

Solution

No, a subclass can always widen the access when overriding a method. There's no way to prevent that. Usually however, when I override a method I rarely change visibility from protected to public. Documenting the purpose of the method carefully might be enough to convince the implementer that it would be a bad idea in this case.

If you really want to encapsulate the behavior in a private way, you could do something along the following lines:

abstract class YourClass {
    private HandlerInterface unexposedHandler;

    YourClass(HandlerInterface handler) {
        unexposedHandler = handler;
    }

    public Object methodIWantToExpose(){
        // ... 
        handler.methodIDontWantExposed();
        // ...
    }
}

With Java 8 you could even make `HandlerInterface` a functional interface and conveniently use a lambda as follows:

class YourSubClass extends YourClass {
    YourSubClass() {
        super(() -> {
            System.out.println("This is the unexposed code");
        });
    }

    ...
}

Problem

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)?

Original source

Related problems