假设我们有一个泛型类,它实现了如下的泛型接口
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();
}
在接口中传递的类型参数是什么?还有,传递给GenericClass内部嵌套类的类型参数是什么?
我将把你的评论当作实际问题:
如果我像这样创建一个GenericClass的新实例:new GenericClass,那么它实现的接口也将是GenericInterface,内部类也将是AnotherClass
是的,应该是GenericInterface<Integer>
。不,不会是AnotherClass<Integer>
。
class GenericClass<T>
引入了一个类型参数T
,它可以与一般的interface
一起使用。现在要小心了:嵌套在GenericClass
中的class AnotherClass<T>
引入了另一个类型参数T
,隐藏了GenericClass
引入的类型参数。
如果您希望AnotherClass
使用GenericClass
的T
,那么只需跳过<T>
以使用AnotherClass
。
在接口中传递的类型参数是什么?
GenericClass
声明中给出的值。
。如果你有new GenericClass<Integer>()
,那么接口将是GenericInterface<Integer>
。
传递给GenericClass内部嵌套类的类型参数是什么?
AnotherClass
声明中给出的值。
。如果您有new AnotherClass<String>()
,那么aVariable
的类型将是String
。即使外部类是GenericClass<Integer>
也是如此。
如果你使用一个好的IDE,那么它可能会告诉你AnotherClass
的T
是隐藏了GenericClass
的T
。