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
I've written this sample using generics based on your needs.
class Parent {
public T foo() {
return (T)this;
}
}
class Child extends Parent {
}
class AnotherChild extends Parent {
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p);
Child c = p.foo();
System.out.println(c);
//throws ClassCastException here since Child is not AnotherChild
AnotherChild ac = p.foo();
System.out.println(ac);
}
}