Occasionally, I want to write an interface that provides some complex method, and I want to make that a default method that uses some protected helper methods.
The objective is such that I can later on change the logic in the complex method and have the changes apply to all implementations of the interface, some of which may not be mine.
But there's no such thing as protected interface methods in Java, so the code I end up writing looks like this:
public interface SomeInterface {
/** Don't override this, override a() and b() instead */
/* final */ default void doSomething() {
// complex code involving a() and b()
}
/** Don't call this directly, use doSomething() instead */
/* protected */ void a();
/** Don't call this directly, use doSomething() instead */
/* protected */ void b();
}
I also can't use an abstract class since Java doesn't support multiple inheritance. Is there any workaround to this problem?
doSomething
being tied to abstract protected methods as you weaken encapsulation (you make the internal workings ofdoSomething
part of its public specification and you couple that base class to all future sub classes. And trying to achieve this with comments in an interface just makes things worse. I'm not sure what Java's equivalent of C#'sAction
is, but you can easily achieve what you want with the interface definingvoid doSomething(Action a, Action b)