何时使用泛型?

编程入门 行业动态 更新时间:2024-10-27 00:25:33
本文介绍了何时使用泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有:

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.

更多推荐

何时使用泛型?

本文发布于:2023-11-16 17:27:22,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!