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


当前回答

多态性一词来自:

形态性=改变的能力

在编程中,多态性是一种“技术”,它允许您将一个对象“看作”不止一种类型的事物。例如:

学生对象也是人对象。如果你“看”这个学生,你可能会问他要学生证。你不能总是对一个人这么做,对吧?(一个人不一定是学生,因此可能没有学生证)。然而,每个人可能都有名字。学生也一样。

底线是,从不同的“角度”“看”同一个对象可以给你不同的“视角”(即不同的属性或方法)

因此,这种技术可以让你构建可以从不同角度“观察”的东西。

为什么我们使用多态性?首先……抽象。在这一点上,它应该是足够的信息:)

其他回答

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

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

编辑:固定破碎的链接。

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

多态性字面上的意思是多种形状。(或多种形式): 对象来自不同的类和同名方法,但工作流不同。 一个简单的例子是:

假设一个人X。

他只是一个人,但他的行为却像许多人一样。 你可能会问:

他是他母亲的儿子。 朋友对朋友。 兄弟之于姐妹。

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

在面向对象编程中,多态性指的是编程语言根据对象的数据类型或类对对象进行不同处理的能力。更具体地说,它是为派生类重新定义方法的能力。