Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 843
chaplean Avatar asked Jan 05 '14 12:01

chaplean


People also ask

What is generic class and generic method in Java?

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.

What is generic type class in Java?

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.

What are generic methods generic methods are the methods defined in a generic class?

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.


1 Answers

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
like image 148
Bohemian Avatar answered Sep 20 '22 04:09

Bohemian