Why does Wikipedia say “Polymorphism is not the sa

2019-02-13 20:05发布

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.

7条回答
够拽才男人
2楼-- · 2019-02-13 20:37

Overloading is having, in the same class, many methods with the same name, but differents parameters.

Overriding is having, in an inherited class, the same method+parameters of a base class. Thus, depending on the class of the object, either the base method, or the inherited method will be called.

Polymorphism is the fact that, an instance of an inherited class can replace an instance of a base class, when given as a parameters.

E.g. :

class Shape {
  public void draw() {
    //code here
  }
  public void draw(int size) {
    //this is overloading 
  }
}

class Square inherits Shape {
  public void draw() {
    //some other code : this is overriding
  }

  public void draw(color c) {
    //this is overloading too
  }
}

class Work {
  public myMethod(Shape s) {
    //using polymophism, you can give to this method
    //a Shape, but also a Square, because Square inherits Shape.
  }
}

See it ? Polymorphing is the fact that, the same object, can be used as an instance of its own class, its base class, or even as an interface.

查看更多
登录 后发表回答