我什么时候应该使用泛型来定义类型之间的关系? [英] When should I use generics to define relationships between types?

查看:133
本文介绍了我什么时候应该使用泛型来定义类型之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里使用泛型时会产生一些混乱。我查看了 Java Generics?,但仍然有一些问题。

Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.

说我有:

public class Honda implements ICar(){
}

public class Opel implements ICar(){
}

我应该使用:

public class Person{
    ICar car;
    .
    .
    public Person (ICar c){
        car = c;
    }
}

public class Person<T extends ICar>{
    T car;
    .
    .
    public Person(T c){
        car = c;
    }
}

还是取决于执行的任务?

or does it depend on the tasks performed?

泛型仅用于聚合关系(容器等);也就是说,它们只用于收藏吗?

Are generics only for aggregation relationships (containers etc); that is, are they just used for 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天全站免登陆