什么是多态性,它的用途是什么,如何使用它?
当前回答
多态性是:
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()实例
其他回答
我知道这是一个有很多好答案的老问题,但我想用一句话来回答:
将派生类型视为其基类型。
上面有很多例子可以说明这一点,但我觉得这是一个很好的简明答案。
从理解和应用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.
多态:
根据类的实例而不是引用变量的类型执行不同的执行。
接口类型引用变量可以引用实现该接口的任何类实例。
通常这指的是A类型对象的行为与b类型对象相似的能力。在面向对象编程中,这通常是通过继承来实现的。一些维基百科的链接来阅读更多:
面向对象编程中的多态性 类型多态性
编辑:固定破碎的链接。
多态性字面上的意思是多种形状。(或多种形式): 对象来自不同的类和同名方法,但工作流不同。 一个简单的例子是:
假设一个人X。
他只是一个人,但他的行为却像许多人一样。 你可能会问:
他是他母亲的儿子。 朋友对朋友。 兄弟之于姐妹。