The difference between overloading inheritance overwriting and polymorphism in Java

  • 2020-04-01 03:24:37
  • OfStack

The difference between overloading, inheritance, overwriting and polymorphism:

1) inheritance is when a subclass gets a member of a parent class.
2) override is a method to reimplement a parent class after inheritance.
3) overloading is the same method in a class with a series of arguments with different names.
4) polymorphism is to avoid bloated and difficult to maintain code due to heavy overloading in parent classes.

An interesting statement I read online is that inheritance is the way a subclass USES its parent, while polymorphism is the way a superclass USES its child.

The following examples include these four implementations:

Class Triangle extends Shape {   Public int getSides () {
    Return 3;
  } } Class Rectangle extends Shape {   Public int getSides(int I) {
    Return the I;
  } } Public class Shape {   Public Boolean isSharp () {     Return true;   }   Public int getSides () {
    Return 0;
  }
  Public int getSides Triangle (tri) {
    Return 3;
  }
  Public int getSides Rectangle (rec) {
    The return of 4;
  }   Public static void main(String[] args) {     Triangle tri = new Triangle();
    System.out.println(" Triangle is a type of sharp? "+ strategy isSharp ());     Shape Shape = new Triangle();
    System.out.println(" My shape has "+ shape.getsides () +" sides. ");   } } Red is overloading, green is overwriting, blue is inheritance, and pink is polymorphism

Note that the method for the Triangle class is overridden, and the method for the Rectangle class is overloaded.
Compare the red and pink parts to see the advantages of polymorphic overloading: if overloading is used, each subclass overloads a method to get the number of edges. If polymorphic, then the parent class only provides an interface to get the number of edges, as for which shape to get the number of edges, and how to get them, respectively in the subclass implementation (override).


Related articles: