在下列情况下,内部类和接口应该有什么类型参数?



假设我们有一个泛型类,它实现了如下的泛型接口

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使用GenericClassT,那么只需跳过<T>以使用AnotherClass

在接口中传递的类型参数是什么?

GenericClass声明中给出的值。

。如果你有new GenericClass<Integer>(),那么接口将是GenericInterface<Integer>

传递给GenericClass内部嵌套类的类型参数是什么?

AnotherClass声明中给出的值。

。如果您有new AnotherClass<String>(),那么aVariable的类型将是String。即使外部类是GenericClass<Integer>也是如此。

如果你使用一个好的IDE,那么它可能会告诉你AnotherClassT隐藏了GenericClassT

相关内容

最新更新