什么是多态性,它的用途是什么,如何使用它?
当前回答
从理解和应用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.
其他回答
我正在浏览另一篇完全不同的文章。多态性出现了……现在我认为我知道多态性是什么....但显然不是用这种美丽的方式解释的。想把它写在某个地方。更好的是分享它…)
http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife
从这部分开始阅读:
…多态性。这是一种很奇怪的说法,不同的名词可以有相同的动词。
通常这指的是A类型对象的行为与b类型对象相似的能力。在面向对象编程中,这通常是通过继承来实现的。一些维基百科的链接来阅读更多:
面向对象编程中的多态性 类型多态性
编辑:固定破碎的链接。
多态性是一种将对象类视为父类的能力。
例如,假设有一个类叫Animal,还有一个类叫Dog,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:
Dog* dog = new Dog;
Animal* animal = dog;
在编码术语中,多态性是指您的对象可以通过继承等方式以多种类型存在。如果你创建了一个名为“Shape”的类,它定义了对象的边数,那么你可以创建一个继承它的新类,如“Square”。当你随后创建一个“Square”实例时,你可以根据需要将它从“Shape”前后转换为“Square”。
我知道这是一个有很多好答案的老问题,但我想用一句话来回答:
将派生类型视为其基类型。
上面有很多例子可以说明这一点,但我觉得这是一个很好的简明答案。