参数多态性与亚型多态性之间的概念差异? [英] Conceptual difference between parametric polymorphism and subtype polymorphism?

查看:114
本文介绍了参数多态性与亚型多态性之间的概念差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过阅读维基百科,但它在多态性问题上非常密集(特别是与Java相关)。我的理解是亚型多态与子类型有关,参数多态与在不同对象/类之间推广的方法有关吗?我缺少什么?

I've tried to read through wikipedia but it's so dense on the subject of polymorphism (specifically related to Java). My understanding is subtype polymorphism is related to subtyping and parametric polymorphism is related to methods being generalized across different objects/classes? What am I missing?

推荐答案

正如文章所述


参数多态允许一般编写函数或数据类型,以便它可以相同地处理值而不依赖于它们的类型......参数多态也可以在几种面向对象的语言中使用,它通常以泛型的名称命名(例如,Java)或模板(C ++和D)

Parametric polymorphism allows a function or a data type to be written generically, so that it can handle values identically without depending on their type ... Parametric polymorphism is also available in several object-oriented languages, where it often goes under the name "generics" (for example, Java) or "templates" (C++ and D)

那么这意味着什么(例如)你可以创建一个带有 somethings 列表的函数,无论 somethings 是什么,该函数都可以正常工作。想一个返回Collection中元素数量的方法。您可以传入任何类型元素的列表,它将返回一个答案。您不必为传入的每种列表重写该函数。

So what this means (as an example) is you can make a function that takes a list of somethings, and the function can work no matter what those somethings are. Think of a method that returns the number of elements in a Collection. You can pass in a list of any type of elements, and it will return an answer. You don't have to rewrite the function for every kind of list you pass in.


有些语言采用子类型来限制可以在特定多态性情况下使用的类型范围。在这些语言中,子类型多态性(有时称为包含多态性或动态多态性[需要引用])允许编写一个函数来获取某个类型T的对象,但如果通过则也能正常工作一个属于类型S的对象,它是一个子类型T

Some languages employ the idea of subtyping to restrict the range of types that can be used in a particular case of polymorphism. In these languages, subtype polymorphism (sometimes referred to as inclusion polymorphism or dynamic polymorphism[citation needed]) allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T

换句话说,你可以拥有一个带动物的方法作为一个参数,但你也可以将猫或狗传入它,因为猫和狗是动物。

In other words, you can have a method that takes an Animal as a parameter but you can also pass in a Cat or a Dog into it because Cats and Dogs are animals.

这篇关于参数多态性与亚型多态性之间的概念差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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