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


当前回答

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

c++中的多态性

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

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

Type1 x;
Type2 y;

f(x);
f(y);

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

(继续在Polymorphism in c++)

其他回答

通常这指的是A类型对象的行为与b类型对象相似的能力。在面向对象编程中,这通常是通过继承来实现的。一些维基百科的链接来阅读更多:

面向对象编程中的多态性 类型多态性

编辑:固定破碎的链接。

OOP中的多态性意味着一个类可以有不同的类型,继承是实现多态性的一种方式。

for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well. so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.

在编码术语中,多态性是指您的对象可以通过继承等方式以多种类型存在。如果你创建了一个名为“Shape”的类,它定义了对象的边数,那么你可以创建一个继承它的新类,如“Square”。当你随后创建一个“Square”实例时,你可以根据需要将它从“Shape”前后转换为“Square”。

我正在浏览另一篇完全不同的文章。多态性出现了……现在我认为我知道多态性是什么....但显然不是用这种美丽的方式解释的。想把它写在某个地方。更好的是分享它…)

http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife

从这部分开始阅读:

…多态性。这是一种很奇怪的说法,不同的名词可以有相同的动词。

多态是指您可以将对象视为某个对象的通用版本,但当您访问它时,代码将确定它的确切类型并调用相关代码。

下面是一个c#的例子。在控制台应用程序中创建四个类:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

现在在控制台应用程序模块的Main()中创建以下内容:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

在这个例子中,我们创建了一个基类Vehicle的列表,它不知道它的每个子类有多少个轮子,但是知道每个子类负责知道它有多少个轮子。

然后我们将自行车、汽车和卡车添加到列表中。

接下来,我们可以循环遍历列表中的每个Vehicle,并将它们都视为相同的,但是当我们访问每个Vehicles 'Wheels'属性时,Vehicle类将该代码的执行委托给相关的子类。

该代码被称为多态代码,因为执行的确切代码是由在运行时引用的子类决定的。

我希望这对你有所帮助。