The difference between overloading and overriding

This article is transcoded by Jianyue SimpRead, the original address blog.csdn.net

1. First of all, understand what coverage is?

· Take a chestnut

public class Main {
	public static void main(String[] args) {
		new Father().print();
		new Son().print();
	}
}
 
class Father{
	 public void print(){
		 System.out.println("father");
	 }
}
class Son extends Father{
	@Override
	public void print() {
		System.out.println("SON");
	}		
}

· Running screenshots

In this example, the subclass inherits the parent class, but overrides the parent class's methods, soAlthough it is a method obtained from the parent class, it is different from the parent class method after overriding, so it is called overriding(that is, the subclass method overrides the parent class method)

1. What is overloading?

· Take a chestnut

public class Main {
	public static void main(String[] args) {
		new Test().print();
		new Test().print(3);
		new Test().print(3,"双参");
	}
}
 
class Test{
	 public void print(){
		 System.out.println("无参");
	 }
	 public void print(int i){
		 System.out.println(i+" "+"单参");
	 }
	 public void print(int i,String j){
		 System.out.println(i+" "+j);
	 }
}

· Running screenshots

In this example, multiple print methods are written, but the parameters are different, so they can be run. This is the meaning of overloading. A class can have multiple methods with the same name and different parameters (different parameter lists).

From the above example, we can see some differences between overriding and overloading, but there are still some differences that are no longer verified by code, as follows

the difference

cover

overload

Realize

Subclass overrides parent class method

Create multiple methods with the same name in the same class

parameter

Same name as parent class

Different parameters with the same name as other methods

return

The return type of the subclass and the superclass should be consistent

no such requirement

permission

Subclasses cannot override private methods of superclasses

no such requirement

A method in a parent class can only be overridden once in a subclass

Overloading can be done multiple times as long as the parameters are different

Overriding is an overriding of the parent class method

Methods in the same class can be overloaded

Override to require subclasses to throw fewer exceptions than superclasses

no such requirement

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324134445&siteId=291194637