OOP in Java: Class inheritance with method chaining
java, oop
Solution
A method in the parent class that returns `this` will still return a reference to the object of the child class. You will only be able to treat it as an object of the parent class (unless you cast it) but it will actually be of its original type.
You could consider using generics like this:
// This seems a bit too contrived for my liking. Perhaps someone else will have a better idea.
public class Parent<T extends Parent<T>> {
T foo () {
return (T) this;
}
}
public class Child extends Parent<Child> {
public void bar () {
Child c = foo();
}
}
Problem
I have a parent class, which defines a collection of chainer methods (methods that return "this"). I want to define multiple child classes that contain their own chainer methods but that also "override" the parent methods so that an instance of the child class is returned instead of the parent class. I don't want to have to repeat the same methods in each child class, which is why I have a parent class that contains the methods that all the child classes share. Thanks. ``` class Chain { public Chain foo(String s){ ... return this; } } class ChainChild extends Chain { //I don't want to add a "foo" method to each child class /* public ChildChain foo(String s){ ... return this; } */ public ChainChild bar(boolean b){ ... return this; } } ChainChild child = new ChainChild(); child.foo().bar(); //compile error: foo() returns a "Chain" object which does not define the bar() method. ```