泛型编程是多态的例子吗? [英] Is generic programming an example of polymorphism?

查看:256
本文介绍了泛型编程是多态的例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个家庭作业任务(一个项目),其中一个标准是我必须利用多态性来显着提高我的代码的整体质量或功能。



我做了一个如下所示的哈希表:

  public class HashTable< E extends Hashable> {
...
}

Hashable是我做的一个接口有一个hash()函数。



我知道使用泛型这种方式可以提高我的代码的质量,因为现在HashTable可以使用几乎任何我想要的类型例如,只是整数或字符串)。但我不确定它是否显示出多态性。



我认为它的确如此,因为E可以是任何实现Hashable的类型。换句话说,HashTable是一个可以与(实际上)任何类型工作的类。



但我不太确定 - 多态性?也许我可以澄清究竟是什么多态性?



感谢您的提前!






编辑:在收到以下答案后(请参阅:第一个回答得到了),我阅读了维基百科的文章,并且遇到了这个问题:

在面向对象编程社区中,使用参数多态的编程往往是称为泛型编程。 (强调增加了)

解决方案

简而言之,多态是指拥有许多共享公共基类(或接口) ,并将他们全部视为共同基础的成员,而不需要知道或关心他们是哪个特定的继承阶级,或者他们如何执行共同职能。在面向对象的编程中,多态给你提供了一个相对较高层次的问题域的部分视图 - 你说的是:这段代码并不关心这些对象的具体细节,只是它们实现了一些常用函数X ,Y,Z或只是它们都是基本类 BaseClass。



您示例使用多态,因为您定义了一个 Hashable 基类 - 并提供一个函数,仅关注它接收的对象的那个方面。 Hashable 对象可能有多种形式,但是您的代码将它们全部视为单个基本类型。


I'm working on a homework assignment (a project), for which one criterion is that I must make use of polymorphism in a way which noticeably improves the overall quality or functionality of my code.

I made a Hash Table which looks like this:

public class HashTable<E extends Hashable>{
    ...
}

where Hashable is an interface I made that has a hash() function.

I know that using generics this way improves the quality of my code, since now HashTable can work with pretty much any type I want (instead of just ints or Strings for example). But I'm not sure if it demonstrates polymorphism.

I think it does, because E can be any type that implements Hashable. In other words HashTable is a class which can work with (practically) any type.

But I'm not quite sure - is that polymorphism? Perhaps can I get some clarification as to what exactly polymorphism is?

Thanks in advance!


Edit: After receiving the answer below (see: first answer received), I read the Wikipedia article, and came across this:

"In the object-oriented programming community, programming using parametric polymorphism is often called generic programming." (emphasis added)

解决方案

Polymorphism is, in a nutshell, taking many different classes which share a common base class (or interface), and treating them all as members of that common base, without knowing or caring which particular inheriting class they are or how precisely they implement the common functions. In object oriented programming, polymorphism gives you a relatively high-level view of that part of your problem domain - you're saying, "This code doesn't care about the specific details of these objects - just that they implement some common functions X,Y,Z," or "just that they're all of the basic class BaseClass."

Your example uses polymorphism, because you define a Hashable base class - and provide a function that cares only about that aspect of the objects it receives. Hashable objects may have many forms, but your code treats them all as a single basic type.

这篇关于泛型编程是多态的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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