<分区>
给定一个通用接口(interface):
public interface I<E> {
public int interfaceMethod(E s);
}
和一个实现接口(interface)的泛型类
public class A<T> implements I<T> {
private T val;
public A(T x) {
val = x;
}
public int interfaceMethod(T val) {
// looks like T should be of the same type as instance variable 'val'
return 0;
}
}
为什么下面的工作?
public class Run {
public static void main(String[] args) {
A a = new A<String>("hello");
System.out.println(a.interfaceMethod(100)); \\ returns 0
}
}
我希望 class A
中定义的 interfaceMethod
方法的 T
类型参数将方法限制为具有相同类型的参数就像提供给 A
的构造函数一样。 (在本例中为 String
)。
为什么 a.interfaceMethod
不需要 String
类型的参数?