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!
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With