Define generic Type of parent class method depending on subclass Type in Java

generics, java, subclassing

Solution

You want this:

public class Parent<T extends Parent<T>> {
    public T foo() {
        return (T)this;
    }
}

public class Child extends Parent<Child> {
    public void childMethod() {
        System.out.println("childMethod called");
    }
}

Child child = new Child();
child.foo().childMethod(); // compiles

Problem

Is it possible to dynamically identify T as a return type depending on subclass Type? I want something like the following: ``` public class Parent { public <T extends Parent> T foo() { return (T)this; } } public class Child extends Parent { public void childMethod() { System.out.println("childMethod called"); } } ``` And then to call: ``` Child child = new Child(); child.foo().childMethod(); ``` Without defining the type like so: ``` Child child = new Child(); child.foo().<Child>childMethod(); // compiles fine ``` Thanks in advance!

Original source