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


当前回答

从理解和应用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.

其他回答

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

多态性允许相同的例程(函数、方法)作用于不同的类型。

由于许多现有的答案将子类型与多态性混为一谈,这里有三种实现多态性的方法(包括子类型)。

参数化(泛型)多态性允许一个例程接受一个或多个类型参数,以及正常参数,并在这些类型上运行。 子类型多态性允许例程对其参数的任何子类型进行操作。 临时多态性通常使用例程重载来授予多态行为,但也可以参考其他多态性实现。

参见:

http://wiki.c2.com/?CategoryPolymorphism

https://en.wikipedia.org/wiki/Polymorphism_ (computer_science)

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

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

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

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

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

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

编辑:固定破碎的链接。