Reputation: 63
Suppose we have a generic class that implements a generic interface like this
GenericClass.java
public class GenericClass<T> implements GenericInterface<T> {
private class AnotherClass<T> {
T aVariable;
}
@Override
public T aMethod() {
return null;
}
}
GenericInterface.java
public interface GenericInterface<T> {
T aMethod();
}
What would be the type parameter passed on in the interface? Also, what would be the type parameter passed to the nested class inside GenericClass.
Upvotes: 0
Views: 114
Reputation: 4723
I'll take your comment as the actual question:
If I create a new instance of GenericClass like this: new GenericClass then will the interface it implements also be GenericInterface and will the inner class als be AnotherClass
Yes, it's gonna be GenericInterface<Integer>
. No, it's not gonna be AnotherClass<Integer>
.
class GenericClass<T>
introduces a type-parameter T
that can be used e.g. with a generic interface
like you do. Now be careful: class AnotherClass<T>
that is nested within GenericClass
introduces another type-parameter T
that hides the one that GenericClass
has introduced.
If you want AnotherClass
to use T
of GenericClass
, then simply skip the <T>
for AnotherClass
.
Upvotes: 4
Reputation: 159086
What would be the type parameter passed on in the interface?
The one given on the GenericClass
declaration.
E.g. if you have new GenericClass<Integer>()
, then the interface would be GenericInterface<Integer>
.
What would be the type parameter passed to the nested class inside GenericClass.
The one given on the AnotherClass
declaration.
E.g. if you have new AnotherClass<String>()
, then aVariable
would have type String
. That is true even if the outer class is a GenericClass<Integer>
.
If you use a good IDE, then it would likely tell you that the T
for AnotherClass
is hiding the T
for GenericClass
.
Upvotes: 1