这个问题在这里已有答案:
给定一个通用接口:
public interface I<E> {
public int interfaceMethod(E s);
}
以及实现接口的泛型类
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
类型的参数?
3 回答
发生这种情况是因为您忽略了警告“Raw a of parameter a”(或类似的东西)
使用:
当忽略通用相关警告时,代码可以在不应该编译时进行编译 .
这是有效的,因为
a
实例仅键入A
类你应该这样输入:
如果你不指定参数,你将能够放置所有数据类型,如
String
,int
等 .而其他答案解释了通常应该出现编译器警告 . 我正在寻找的解释以@JB Nizet提供的link to a previous post的形式出现 .
T t = new T<S>()
是不一样的
T<S> t = new T<S>()
第一个是 raw type 的示例 . 我感兴趣 why 这个工作(即......如果它编译并且不会抛出运行时错误)那么必须有一些东西 .
该帖子的答案是详细的,并解释了为什么这个编译(长话短,向后兼容) . 这篇文章详细介绍了Java的类型系统的含义 .