何时使用泛型? [英] When to use generics?

查看:108
本文介绍了何时使用泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我有:

  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>

Java泛型?



我想我问的是泛型只是用于集合?

解决方案

人通常没有使用某种类型的汽车参数化。只有非常讨厌的人被他们的汽车所定义。人们也会改变车辆(及时)。所以我不会参数化类,如果只是为了语义。



在进入这样的编程细节之前,想想你想从现实世界中模拟出什么。

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:

Java Generics?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆