何时使用泛型? [英] When to use generics?
问题描述
假设我有:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
$
公共班人员{
ICar car;
。
。
public Person(ICar c){
car = c;
code
public class Person< T extends ICar> {
T car;
。
。
public Person(T c){
car = c;
$ b $ p
$ p $或$是否取决于执行的任务?编辑:所以泛型只适用于聚合关系(容器等)?
编辑:这可能有所帮助:
p>
我想我问的是泛型只是用于集合?
解决方案人通常没有使用某种类型的汽车参数化。只有非常讨厌的人被他们的汽车所定义。人们也会改变车辆(及时)。所以我不会参数化类,如果只是为了语义。
在进入这样的编程细节之前,想想你想从现实世界中模拟出什么。
p>
Getting into a little bit of confusion here when to use generics:
Say I have:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
should I use:
public class Person{
ICar car;
.
.
public Person (ICar c){
car = c;
}
}
or
public class Person<T extends ICar>{
T car;
.
.
public Person(T c){
car = c;
}
}
or does it depend on the tasks performed?
EDIT: So is generics only for aggregation relationships (containers etc)?
EDIT: This may help:
I think I am asking is generics just for use with collections?
解决方案 A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.
Think about what you try to mimic from the real world, before going into such programming details.
这篇关于何时使用泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!