Home  >  Article  >  Java  >  The difference between overloading, inheritance, overriding and polymorphism in Java

The difference between overloading, inheritance, overriding and polymorphism in Java

高洛峰
高洛峰Original
2017-01-19 13:58:031271browse

The difference between overloading, inheritance, overwriting 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 subclasses to use parent classes, while polymorphism is a method for parent classes to use subclasses.

The following example includes 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 It 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, you must overload a method for obtaining the number of edges in the parent class corresponding to each subclass; if you use multiple state, the parent class only provides an interface for obtaining the number of edges. As for obtaining the number of edges of which shape and how to obtain it, each child class can implement (rewrite) it.

For more articles related to the differences between overloading, inheritance, rewriting and polymorphism in Java, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn