维基百科为什么说“多态与方法重载或方法重写不同". [英] Why does Wikipedia say "Polymorphism is not the same as method overloading or method overriding."

查看:94
本文介绍了维基百科为什么说“多态与方法重载或方法重写不同".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,找不到任何类似的问题.

这是我从 Wikipedia 中获得的段落:

多态与方法重载或方法重载不同.多态仅与将特定实现应用于接口或更通用的基类有关.方法重载是指在同一类中名称相同但签名不同的方法.方法重写是子类替换其父方法的一个或多个方法的实现的地方.方法重载和方法重载本身都不是多态性的实现.

这里有人可以更清楚地解释它吗,特别是多态与方法重写不一样"部分吗?我现在很困惑.预先感谢.

解决方案

多态性(很简单地说)是可以在期望具有基类的情况下使用派生类的一种可能性:

class Base {

}

class Derived extends Base  {

}

Base v = new Derived(); // OK

另一方面,方法重写是Wiki所说的一种在派生类中更改方法行为的方法:

class Shape  {
  void draw() { /* Nothing here, could be abstract*/ }
}

class Square extends Shape  {
  @Override
  void draw() { /* Draw the square here */ }
}

重载与继承无关,它允许定义更多具有相同名称的函数,这些函数的唯一区别仅在于所采用的参数.

I have looked around and could not find any similar question.

Here is the paragraph I got from Wikipedia:

Polymorphism is not the same as method overloading or method overriding. Polymorphism is only concerned with the application of specific implementations to an interface or a more generic base class. Method overloading refers to methods that have the same name but different signatures inside the same class. Method overriding is where a subclass replaces the implementation of one or more of its parent's methods. Neither method overloading nor method overriding are by themselves implementations of polymorphism.

Could anyone here explain it more clearly, especially the part "Polymorphism is not the same as method overriding"? I am confused now. Thanks in advance.

解决方案

Polymorphism (very simply said) is a possibility to use a derived class where a base class is expected:

class Base {

}

class Derived extends Base  {

}

Base v = new Derived(); // OK

Method overriding, on the other hand, is as Wiki says a way to change the method behavior in a derived class:

class Shape  {
  void draw() { /* Nothing here, could be abstract*/ }
}

class Square extends Shape  {
  @Override
  void draw() { /* Draw the square here */ }
}

Overloading is unrelated to inheritance, it allows defining more functions with the same name that differ only in the arguments they take.

这篇关于维基百科为什么说“多态与方法重载或方法重写不同".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆