什么是多态性,它的用途是什么,如何使用它?


当前回答

在面向对象编程中,多态性指的是编程语言根据对象的数据类型或类对对象进行不同处理的能力。更具体地说,它是为派生类重新定义方法的能力。

其他回答

一般来说,它是一种使用相同或表面上相似的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.

我为另一个问题提供了多态性的高级概述:

c++中的多态性

希望能有所帮助。一个提取…

...从简单的测试和[多态性]定义开始会有所帮助。考虑下面的代码:

Type1 x;
Type2 y;

f(x);
f(y);

这里,f()是执行一些操作,并被赋予值x和y作为输入。要具有多态性,f()必须能够操作至少两种不同类型的值(例如int和double),查找并执行适合类型的代码。

(继续在Polymorphism in c++)

多态性使您能够创建一个模块调用另一个模块,并且在编译时依赖于控制流而不是控制流。

通过使用多态性,高级模块不依赖于低级模块。两者都依赖于抽象。这有助于我们应用依赖倒置原则(https://en.wikipedia.org/wiki/Dependency_inversion_principle)。

这就是我找到上面定义的地方。在视频中大约50分钟,教练解释了上述内容。 https://www.youtube.com/watch?v=TMuno5RZNeE

多态是对象的一种能力,可以表现为多种形式。 例如,在人类课堂上,当我们谈论关系时,一个人可以表现为多种形式。 男人对儿子是父亲,对妻子是丈夫,对学生是老师。

什么是多态性?

多态性是一种能力:

调用专门化类型实例上的操作时,只知道其泛化类型,而调用专门化类型的方法,而不调用泛化类型的方法: 这就是动态多态性。 定义几个具有保存名称但参数不同的方法: 这是静态多态。

首先是历史定义,也是最重要的。

多态用于什么?

它允许创建类层次结构的强类型一致性,并做一些神奇的事情,比如管理不同类型的对象列表,而不知道它们的类型,只知道它们的父类型之一,以及数据绑定。

强类型和弱类型

样本

这里有一些形状,如点、线、矩形和圆,它们的Draw()操作要么不接受任何参数,要么使用参数设置超时来删除它们。

public class Shape
{
 public virtual void Draw()
 {
   DoNothing();
 }
 public virtual void Draw(int timeout)
 {
   DoNothing();
 }
}

public class Point : Shape
{
 int X, Y;
 public override void Draw()
 {
   DrawThePoint();
 }
}

public class Line : Point
{
 int Xend, Yend;
 public override Draw()
 {
   DrawTheLine();
 }
}

public class Rectangle : Line
{
 public override Draw()
 {
   DrawTheRectangle();
 }
}

var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };

foreach ( var shape in shapes )
  shape.Draw();

这里Shape类和Shape. draw()方法应该被标记为抽象。

它们不是用来理解的。

解释

如果没有多态性,使用抽象-虚拟-重写,在解析形状时,只调用Spahe.Draw()方法,因为CLR不知道要调用什么方法。它调用我们所作用的类型的方法,这里的类型是Shape,因为列表声明。所以代码什么都不做。

通过多态性,CLR能够推断我们使用所谓的虚拟表所操作的对象的真实类型。它调用good方法,如果Shape是Point调用Shape。draw ()所以代码画出了形状。

更多的阅读

c# -多态性(1级)

Java中的多态性(要求等级2)

多态性(c#编程指南)

虚方法表