The difference between overloading, inheritance, rewriting and polymorphism in Java
The difference between overloading, inheritance, rewriting and polymorphism:
1) Inheritance is when a subclass gets a member of its parent class. 2) Overriding is a method that re implements a parent class after inheritance. 3) Overloading is a series of methods with different parameters and the same name in a class. 4) Polymorphism is to avoid code bloated and difficult to maintain caused by a large number of overloads in the parent class.
There is an interesting saying on the Internet: inheritance is the way that a subclass uses its parent, while polymorphism is the way that a parent uses its subclass.
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 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){ return 4 ; } public static void main(String[] args) { Triangle tri = new Triangle(); System.out.println(“Triangle is a type of sharp? ” + tri. isSharp()); Shape shape = new Triangle(); System. out. println(“My shape has ” + shape.getSides() + ” sides.”); Red is overloaded, green is rewritten, blue is inheritance, and pink is polymorphic
Note that the method of the triangle class is overridden, while the method of the rectangle class is overloaded. Comparing the red and pink parts, we can find the advantages of polymorphic pair overloading: if overloading is used, a method to obtain the number of edges should be overloaded for each subclass in the parent class; If polymorphism is used, the parent class only provides an interface to obtain the number of edges. As for which shape of edges to obtain and how to obtain, they are implemented (overridden) in the subclass.