The difference between overloading, inheritance, overriding and polymorphism:
1) Inheritance is when a subclass obtains members of the parent class.
2) Overriding is a method of reimplementing the 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 a large number of overloading in the parent class, which will cause the code to be bloated and difficult to maintain.
An interesting statement I saw on the Internet is: inheritance is a method for a subclass to use a parent class, while polymorphism is a method for a parent class to use a 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 overloading, green is overwriting, blue is inheritance, pink is polymorphism
Note that the methods of the Triangle class are overridden, while the methods of the Rectangle class are overloaded.
Comparing the red and pink parts, you can find the advantages of polymorphism over overloading: If you use overloading, a method for obtaining the number of edges must be overloaded in the parent class for each subclass; if you use polymorphism, then The parent class only provides an interface for obtaining the number of sides. As for obtaining the number of sides of which shape and how to obtain it, they are implemented (rewritten) in the subclasses respectively.