So I have a couple of inherited classes defined like so.
class Base {
public Base chainedMethodA() {
// some stuff
return this;
}
}
class Derived extends Base {
public Derived chainedMethodB() {
// some stuff
return this;
}
}
Now, the following code works:
Derived obj = new Derived();
obj.chainedMethodB().chainedMethodA();
But this does not (notice the switched order of function calls):
Derived obj = new Derived();
obj.chainedMethodA().chainedMethodB();
The compiler gives an error on the chainedMethodB() function call. I can understand that this is because when you run chainedMethodA(), it returns an object of type Base, which does not have chainedMethodB defined.
I can think of a few solutions to this problem:
- Chain methods while paying attention to order (call
Derived's methods first, and then callBase's methods). This looks like a very brittle solution. - Override
chainedMethodAinDerivedso it returns an instance ofDerivedinstead ofBase. This looks like a waste of inheritance.
Is there any elegant way around this problem? Maybe some construct that magically changes chainedMethodA to return a Derived instance when called by an object of type Derived, without being explicitly overridden in Derived.
@Override public Derived chainedMethodA() { ... }Derived'schainedMethodAto return an instance ofDerivedthen it can't call the super implementation anyway (because that might return an actualBasewhich isn't aDerived). So you're not losing anything that way, and you allowDerivedobjects to still be used asBases.