在Java中,当有人问:
什么是多态性?
重载或重写是可以接受的答案吗?
我认为事情远不止如此。
如果你有一个抽象基类,它定义了一个没有实现的方法,并且你在子类中定义了这个方法,这仍然是覆盖的吗?
我认为超负荷肯定不是正确的答案。
在Java中,当有人问:
什么是多态性?
重载或重写是可以接受的答案吗?
我认为事情远不止如此。
如果你有一个抽象基类,它定义了一个没有实现的方法,并且你在子类中定义了这个方法,这仍然是覆盖的吗?
我认为超负荷肯定不是正确的答案。
当前回答
术语重载指的是具有相同名称的东西的多个版本,通常是具有不同参数列表的方法
public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }
这些函数可能做同样的事情但你可以选择用ID或名称来调用它。与继承、抽象类等无关。
覆盖通常指的是多态性,就像你在问题中描述的那样
其他回答
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.
重载是指定义两个名称相同但参数不同的方法
重写是通过子类中具有相同名称的函数更改基类的行为。
所以多态性与覆盖有关,但不是真正的重载。
然而,如果有人对“什么是多态性?”这个问题给出了一个简单的“重写”的答案。我要求进一步解释。
多态性是一个对象以多种形式出现的能力。这涉及到使用继承和虚函数来构建可交换的对象族。基类包含虚函数的原型,这些原型可能未实现,也可能具有应用程序指定的默认实现,而各种派生类都以不同的方式实现它们,以影响不同的行为。
重写更像是通过声明一个与上层方法(超级方法)具有相同名称和签名的方法来隐藏一个继承的方法,这为类添加了多态行为。 换句话说,选择要调用的级别方法的决定将在运行时而不是在编译时做出。 这就引出了接口和实现的概念。
多态性涉及到一种语言通过使用单一接口统一处理不同对象的能力;因此,它与覆盖有关,因此接口(或基类)是多态的,实现者是覆盖的对象(同一奖章的两个面)
无论如何,这两个术语之间的区别可以用其他语言更好地解释,比如c++:如果基本函数是虚的,那么c++中的多态对象的行为就像Java对应的对象一样,但如果方法不是虚的,那么代码跳转是静态解析的,并且在运行时不检查真实类型,因此,多态包括对象根据用于访问它的接口而表现不同的能力;让我在伪代码中做一个例子:
class animal {
public void makeRumor(){
print("thump");
}
}
class dog extends animal {
public void makeRumor(){
print("woff");
}
}
animal a = new dog();
dog b = new dog();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
(假设makeRumor不是虚拟的)
Java并没有真正提供这种级别的多态性(也称为对象切片)。
动物a =新狗(); Dog b = new Dog ();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
在这两种情况下,它只会打印woff.. 因为a和b指的是类dog