gpt4 book ai didi

java - 参数多态性和子类型多态性之间的概念区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:54 25 4
gpt4 key购买 nike

我曾尝试通读维基百科,但它对多态性(特别是与 Java 相关)的主题非常详尽。我的理解是子类型多态性与子类型相关,而参数多态性与跨不同对象/类泛化的方法相关?我错过了什么?

最佳答案

As the article says ,

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 是什么,该函数都可以工作.想想一个返回集合中元素数量的方法。您可以传入任何类型元素的列表,它会返回一个答案。您不必为传入的每种列表重写函数。

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

换句话说,您可以拥有一个将 Animal 作为参数的方法,但您也可以将 Cat 或 Dog 传入其中,因为 Cats 和 Dog 是动物。

关于java - 参数多态性和子类型多态性之间的概念区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com