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


当前回答

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

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

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

其他回答

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

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.

多态性是一个对象具有多种形式的能力。在OOP中,多态性最常见的用法是用父类引用引用子类对象。在这个用Java编写的例子中,我们有三种类型的车辆。我们创建了三个不同的对象,并尝试运行他们的轮子方法:

public class PolymorphismExample {

    public static abstract class Vehicle
    {
        public int wheels(){
            return 0;
        }
    }

    public static class Bike extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 2;
        }
    }

    public static class Car extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 4;
        }
    }

    public static class Truck extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 18;
        }
    }

    public static void main(String[] args)
    {
        Vehicle bike = new Bike();
        Vehicle car = new Car();
        Vehicle truck = new Truck();

        System.out.println("Bike has "+bike.wheels()+" wheels");
        System.out.println("Car has "+car.wheels()+" wheels");
        System.out.println("Truck has "+truck.wheels()+" wheels");
    }

}

结果是:

欲了解更多信息,请访问https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java。我希望这能有所帮助。

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

c++中的多态性

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

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

Type1 x;
Type2 y;

f(x);
f(y);

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

(继续在Polymorphism in 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()方法,尽管开发人员无法提前知道用户将选择分数还是复数。