user1589188
user1589188

Reputation: 5736

What does the type parameter in front of method do if not using it as parameter?

If we have an abstract method

public abstract class Test {
  public abstract <T> void method();
}

then all concrete derived classes are forced to have <T> in their method signature:

public class Test1 extends Test {
    public <T> void method() {
        // some code
    }
}

What is the use case of this? What can we do with T? And how does T get its inference from?

Upvotes: 0

Views: 174

Answers (1)

talex
talex

Reputation: 20566

In this situation it is no reason to have generic parameter, but java specification do not forbid it.

Someone who did that just made mistake.

EDIT

PS: I found the case when generic parameter is not in method signature, but still useful. (Thanks to @JimmyB for idea)

Imagine that you have two interfaces:

interface A {}

interface B {}

Also two methods with next signatures:

<T extends A & B> T f1();

<T extends A & B> void f2(T t);

Then you can have method like this:

<T extends A & B> void foo() {
    T t = f1();
    f2(t);
}

It is not exactly method in question because it have constraints on generic parameter, but it is as close as I can get.

Upvotes: 1

Related Questions