什么是多态性,它的用途是什么,如何使用它?
当前回答
多态性字面上的意思是多种形状。(或多种形式): 对象来自不同的类和同名方法,但工作流不同。 一个简单的例子是:
假设一个人X。
他只是一个人,但他的行为却像许多人一样。 你可能会问:
他是他母亲的儿子。 朋友对朋友。 兄弟之于姐妹。
其他回答
通常这指的是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.
多态性是一种将对象类视为父类的能力。
例如,假设有一个类叫Animal,还有一个类叫Dog,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:
Dog* dog = new Dog;
Animal* animal = dog;
让我们打个比方。对于一个特定的音乐剧本,每个演奏它的音乐家都有自己的诠释。
音乐家可以用接口抽象,音乐家所属的流派可以是一个抽象类,它定义了一些全局解释规则,每个演奏的音乐家都可以用具体类建模。
如果你是音乐作品的听众,你可以参考剧本,例如巴赫的“富加与托卡塔”,每个演奏它的音乐家都以自己的方式多态地演奏。
这只是一个可能的设计示例(在Java中):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
多态性允许相同的例程(函数、方法)作用于不同的类型。
由于许多现有的答案将子类型与多态性混为一谈,这里有三种实现多态性的方法(包括子类型)。
参数化(泛型)多态性允许一个例程接受一个或多个类型参数,以及正常参数,并在这些类型上运行。 子类型多态性允许例程对其参数的任何子类型进行操作。 临时多态性通常使用例程重载来授予多态行为,但也可以参考其他多态性实现。
参见:
http://wiki.c2.com/?CategoryPolymorphism
https://en.wikipedia.org/wiki/Polymorphism_ (computer_science)