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


当前回答

如果有人对这些人说CUT

外科医生 发型师 这个演员

会发生什么?

外科医生开始做一个切口。 发型师会开始给某人理发。 行动者会突然停止在当前场景之外的表演, 等待导演指导。

因此,上面的表示说明了什么是OOP中的多态性(相同的名称,不同的行为)。

如果你要去参加面试,面试官要求你在我们坐在的同一个房间里讲述/展示一个多态性的生动例子,比如说-

答案-门/窗

想知道吗?

通过门/窗-人可以进来,空气可以进来,光可以进来,雨可以进来,等等。

为了更好地理解它,以一种简单的方式,我使用了上面的例子。 如果你需要代码参考,请参考上面的答案。

其他回答

什么是多态性?

多态性是一种能力:

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

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

多态用于什么?

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

强类型和弱类型

样本

这里有一些形状,如点、线、矩形和圆,它们的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#编程指南)

虚方法表

多态性是程序员编写同名方法的能力,这些方法根据对象的需要,为不同类型的对象做不同的事情。例如,如果您正在开发一个名为Fraction的类和一个名为ComplexNumber的类,这两个类都可能包含一个名为display()的方法,但它们各自实现该方法的方式不同。例如,在PHP中,你可以这样实现它:

//  Class definitions

class Fraction
{
    public $numerator;
    public $denominator;

    public function __construct($n, $d)
    {
        //  In real life, you'd do some type checking, making sure $d != 0, etc.
        $this->numerator = $n;
        $this->denominator = $d;
    }

    public function display()
    {
        echo $this->numerator . '/' . $this->denominator;
    }
}

class ComplexNumber
{
    public $real;
    public $imaginary;

    public function __construct($a, $b)
    {
        $this->real = $a;
        $this->imaginary = $b;
    }

    public function display()
    {
        echo $this->real . '+' . $this->imaginary . 'i';
    }
}


//  Main program

$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);

echo 'This is a fraction: '
$fraction->display();
echo "\n";

echo 'This is a complex number: '
$complex->display();
echo "\n";

输出:

This is a fraction: 1/2
This is a complex number: 1 + 2i

其他一些答案似乎暗示多态性只与继承一起使用;例如,可能Fraction和ComplexNumber都实现了一个名为Number的抽象类,该类有一个方法display(), Fraction和ComplexNumber都必须实现这个方法。但是您不需要继承来利用多态性。

至少在动态类型语言如PHP(我不知道c++或Java)中,多态性允许开发人员调用方法,而不必事先知道对象的类型,并相信将调用方法的正确实现。例如,假设用户选择创建的数字类型:

$userNumberChoice = $_GET['userNumberChoice'];

switch ($userNumberChoice) {
    case 'fraction':
        $userNumber = new Fraction(1, 2);
        break;
    case 'complex':
        $userNumber = new ComplexNumber(1, 2);
        break;
}

echo "The user's number is: ";
$userNumber->display();
echo "\n";

在这种情况下,将调用适当的display()方法,尽管开发人员无法提前知道用户将选择分数还是复数。

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

我知道这是一个有很多好答案的老问题,但我想用一句话来回答:

将派生类型视为其基类型。

上面有很多例子可以说明这一点,但我觉得这是一个很好的简明答案。

从理解和应用PHP多态性,感谢Steve Guidetti。

Polymorphism is a long word for a very simple concept. Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface. The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task. In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.