Vic*_*tor 11 java generics inheritance
public class B extends C <A> {
}
Run Code Online (Sandbox Code Playgroud)
这是什么意思?C需要扩展A?我提出了什么额外的限制,而不只是说B扩展C?
Emi*_*Sit 18
在这种情况下,C是一个可以采用泛型参数的类,并且您将为其提供特定类型A作为参数.然后,B扩展该特定参数化C.
例如,假设:
class C<T> {
T example();
}
class B extends C<Integer> {
}
Run Code Online (Sandbox Code Playgroud)
然后B.example()会回来Integer.
C<A>并不意味着正在C扩展A,它意味着它可以作为A类型参数。
Comparable<T>这和Comparator<T>java中的接口非常相似。
考虑下面的例子
public class NameSort implements Comparator<Employee> {
public int compare(Employee one, Employee another){
return (int)(one.getName() - another.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
意味着 Comparator 正在使用 Employee 对象根据其名称对它们进行排序。
你还可以举另一个例子
List<String> list = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
此行表示List正在使用String对象作为参数