在Java中,当有人问:

什么是多态性?

重载或重写是可以接受的答案吗?

我认为事情远不止如此。

如果你有一个抽象基类,它定义了一个没有实现的方法,并且你在子类中定义了这个方法,这仍然是覆盖的吗?

我认为超负荷肯定不是正确的答案。


当前回答

多态性是一个对象以多种形式出现的能力。这涉及到使用继承和虚函数来构建可交换的对象族。基类包含虚函数的原型,这些原型可能未实现,也可能具有应用程序指定的默认实现,而各种派生类都以不同的方式实现它们,以影响不同的行为。

其他回答

多态性是一个对象以多种形式出现的能力。这涉及到使用继承和虚函数来构建可交换的对象族。基类包含虚函数的原型,这些原型可能未实现,也可能具有应用程序指定的默认实现,而各种派生类都以不同的方式实现它们,以影响不同的行为。

经典的例子,狗和猫是动物,动物有制造声音的方法。我可以迭代调用makeNoise的动物数组,并期望它们在各自的实现。

调用代码不需要知道它们是什么特定的动物。

这就是我所说的多态性。

没有:

重载是指使用相同的函数名,但接受不同的参数。

重写是指子类用自己的方法替换父类的方法(这本身不构成多态性)。

多态性是后期绑定,例如,基类(父类)方法被调用,但直到运行时应用程序才知道实际对象是什么——它可能是一个方法不同的子类。这是因为任何子类都可以在定义基类的地方使用。

在Java中,你可以在集合库中看到很多多态性:

int countStuff(List stuff) {
  return stuff.size();
}

List是基类,编译器不知道你计数的是链表、向量、数组还是自定义列表实现,只要它像List一样:

List myStuff = new MyTotallyAwesomeList();
int result = countStuff(myStuff);

如果你超载了,你会:

int countStuff(LinkedList stuff) {...}
int countStuff(ArrayList stuff) {...}
int countStuff(MyTotallyAwesomeList stuff) {...}
etc...

编译器会选择countStuff()的正确版本来匹配参数。

多态性简单来说就是“多种形式”。

它不需要继承来实现…作为接口实现,它根本不是继承,服务于多态需求。可以说,接口实现比继承更能满足多态需求。

例如,你会创建一个超类来描述所有会飞的东西吗?我不这么认为。你最好创建一个描述飞行的界面,然后就这样吧。

因此,由于接口描述行为,而方法名描述行为(对程序员来说),将方法重载视为一种较小形式的多态性并不过分。

Polymorphism is a multiple implementations of an object or you could say multiple forms of an object. lets say you have class Animals as the abstract base class and it has a method called movement() which defines the way that the animal moves. Now in reality we have different kinds of animals and they move differently as well some of them with 2 legs, others with 4 and some with no legs, etc.. To define different movement() of each animal on earth, we need to apply polymorphism. However, you need to define more classes i.e. class Dogs Cats Fish etc. Then you need to extend those classes from the base class Animals and override its method movement() with a new movement functionality based on each animal you have. You can also use Interfaces to achieve that. The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods "with same name" but with different parameters on same object or class.