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.
A Generic class can have muliple type parameters.
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 .
A class definition can have more than one type parameter.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
public interface SomeRelatedInterface<T> {
T doSomethingRelated(SomeInterface<T> relative);
}
"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
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