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!
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