什么是多态性,它的用途是什么,如何使用它?
当前回答
多态性允许相同的例程(函数、方法)作用于不同的类型。
由于许多现有的答案将子类型与多态性混为一谈,这里有三种实现多态性的方法(包括子类型)。
参数化(泛型)多态性允许一个例程接受一个或多个类型参数,以及正常参数,并在这些类型上运行。 子类型多态性允许例程对其参数的任何子类型进行操作。 临时多态性通常使用例程重载来授予多态行为,但也可以参考其他多态性实现。
参见:
http://wiki.c2.com/?CategoryPolymorphism
https://en.wikipedia.org/wiki/Polymorphism_ (computer_science)
其他回答
在编码术语中,多态性是指您的对象可以通过继承等方式以多种类型存在。如果你创建了一个名为“Shape”的类,它定义了对象的边数,那么你可以创建一个继承它的新类,如“Square”。当你随后创建一个“Square”实例时,你可以根据需要将它从“Shape”前后转换为“Square”。
在面向对象语言中,多态性允许通过同一个接口处理和处理不同的数据类型。例如,考虑c++中的继承: 类B派生自类A。类型为A*的指针(指向类A的指针)可以用来处理类A的对象和类B的对象。
如果有人对这些人说CUT
外科医生 发型师 这个演员
会发生什么?
外科医生开始做一个切口。 发型师会开始给某人理发。 行动者会突然停止在当前场景之外的表演, 等待导演指导。
因此,上面的表示说明了什么是OOP中的多态性(相同的名称,不同的行为)。
如果你要去参加面试,面试官要求你在我们坐在的同一个房间里讲述/展示一个多态性的生动例子,比如说-
答案-门/窗
想知道吗?
通过门/窗-人可以进来,空气可以进来,光可以进来,雨可以进来,等等。
为了更好地理解它,以一种简单的方式,我使用了上面的例子。 如果你需要代码参考,请参考上面的答案。
多态性一词来自:
多
形态性=改变的能力
在编程中,多态性是一种“技术”,它允许您将一个对象“看作”不止一种类型的事物。例如:
学生对象也是人对象。如果你“看”这个学生,你可能会问他要学生证。你不能总是对一个人这么做,对吧?(一个人不一定是学生,因此可能没有学生证)。然而,每个人可能都有名字。学生也一样。
底线是,从不同的“角度”“看”同一个对象可以给你不同的“视角”(即不同的属性或方法)
因此,这种技术可以让你构建可以从不同角度“观察”的东西。
为什么我们使用多态性?首先……抽象。在这一点上,它应该是足够的信息:)
一般来说,它是一种使用相同或表面上相似的API来为许多不同类型的对象提供接口的能力。有多种形式:
Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism. Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism. Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.