Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference a nested generic parameter in java?

Tags:

java

generics

I'm not sure what the technical term for this is, but consider an interface:

public interface SomeInterface<T> {
     public T doSomething();
}

And then a second interface:

public interface SomeRelatedInterface<T, D extends SomeInterface<T>> {
     public T doSomethingRelated(D relative);
}

Is it possible to craft the second interface to only require one generic parameter, and then have the doSomethingRelated method implicitly extract the return type in its declaration. This is not legal, but this is what I am wondering if can be done in some other means:

public interface <T> SomeRelatedInterface<D extends SomeInterface<T>> {
     public T doSomethingRelated(D relative);
}

EDIT (On posting the bounty): At this point what I am looking for on this question is the reason that the language requires this duplication. That is what has been missing from the answers until now to get one accepted.

like image 476
Yishai Avatar asked Jun 15 '09 15:06

Yishai


People also ask

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

Which reference types Cannot be generic?

Almost all reference types can be generic. This includes classes, interfaces, nested (static) classes, nested interfaces, inner (non-static) classes, and local classes. The following types cannot be generic: Anonymous inner classes .

Can a generic class definition can only have one type parameter?

A class definition can have more than one type parameter.

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).


2 Answers

public interface SomeRelatedInterface<T> {  
    T doSomethingRelated(SomeInterface<T> relative);
}
like image 160
Daniel Moura Avatar answered Sep 20 '22 14:09

Daniel Moura


"At this point what I am looking for on this question is the reason that the language requires this duplication"

Well, the language requires that you define 2 type parameters in your example because there are, um, 2 type parameters in the problem you describe: you wish a method to be variable in both the type T and also in the implementation of SomeInterface.

These are orthogonal considerations and hence you need more than one type parameter to represent them.

Type parameters do not of course need to be defined on a class/interface; they can be defined on a method. J-16 SDiZ's answer allows your related class/interface to have one type parameter only. The second type parameter is then declared only where it is needed, on the doSomethingRelated method

like image 39
oxbow_lakes Avatar answered Sep 19 '22 14:09

oxbow_lakes