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


当前回答

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

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

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

其他回答

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

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

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

在面向对象语言中,多态性允许通过同一个接口处理和处理不同的数据类型。例如,考虑c++中的继承: 类B派生自类A。类型为A*的指针(指向类A的指针)可以用来处理类A的对象和类B的对象。

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

多态性是:

class Cup {
   int capacity
}

class TeaCup : Cup {
   string flavour
}

class CoffeeCup : Cup {
   string brand
}

Cup c = new CoffeeCup();

public int measure(Cup c) {
    return c.capacity
}

你可以只传递一个Cup而不是一个特定的实例。这在一般情况下很有帮助,因为您不必为每个cup类型提供特定的measure()实例

多态:

根据类的实例而不是引用变量的类型执行不同的执行。

接口类型引用变量可以引用实现该接口的任何类实例。