I have some class inheritance SubClass < MidClass < SuperClass and want to perform some TASK upward for all these classes. TASK is quite complex with only minor changes in the 3 classes, which I moved into the private methods m2().
My current solution is very boiler plate:
class SuperClass {
protected void m1() {
//TASK (calls m2())
}
private void m2() {
//...
}
}
class MidClass extends SuperClass {
protected void m1() {
//same TASK (calls m2())
super.m1();
}
private void m2() {
//...
}
}
class SubClass extends MidClass {
protected void m1() {
//same TASK (calls m2())
super.m1();
}
private void m2() {
//...
}
}
Can I exploit some code reuse mechanism instead of copying TASK?
Something like the following, with m1() only in SuperClass, does not work:
class SuperClass {
protected final void m1() {
//TASK (calls m2())
if (!(this.getClass().equals(SuperClass.class))) {
super.m1();
}
}
because super.m1() does not refer to execution of the same inherited method in the context of a super class, but to the overridden method implementation. Since m1() does not exist in Object, I additionally get a compiler error...
Putting TASK in a protected final helper() method in SuperClass and calling helper() instead of copying TASK won't work, since then always SuperClass.m2() gets called.
The only alternative I can think of is slow, complicated and unsafe: using a type token as parameter, i.e. protected final void m1(Class<? extends SuperClass> clazz)
in SuperClass, and fulfilling TASK via reflection (requires to make m2() public static or use setAccessible(true) on m2()).
Do you know some better solution? AOP? Maybe some framework where you can inject a method into classes (as in C#)? Or am I missing something???