In Java, multiple methods in the same class can have the same name, as long as their argument lists are different, which is called method overloading.
Parameter lists are also called parameter signatures, including the type of the parameter, the number of arguments, and the order of the parameters, as long as there is a difference between the parameter list.
Overloading is a fundamental feature of object-oriented.
Let's look at a detailed example below.
- Public class Demo{
- //An ordinary method with no parameters
- void Test(){
- System. Out. println("No parameters");
- }
- //Reload the above method with an integer parameter
- void Test(int a){
- System. Out. println("A:" + a);
- }
- //Reload the above method, and with two parameters
- void Test(int a,int b){
- System. Out. println("A and B:" + a + "" + b);
- }
- //Reload the method above, and with a double-precision parameter
- Double test(double A){
- System. Out. println("Double A:" + a);
- return a*a;
- }
- public static void main(String args[]){
- demo obj= New demo();
- Obj. Test();
- Obj. Test(2);
- Obj. Test(2,3);
- Obj. Test(2.0);
- }
- }
Operation Result:
No parameters
A:2
A and B:2 3
Double a:2.0
From the above example, the reader can see that overloading is a function in a class that has the same function name, but with different parameters. The result of overloading allows a program segment to minimize the kinds of code and methods.
Description
- Different parameter lists include: different numbers, different types, and different order.
- It is not possible to have only parameter variable names.
- As with member methods, construction methods can also be overloaded.
- A method that is declared final cannot be overloaded.
- A method declared as static cannot be overloaded, but can be declared again.
Rules for overloading of methods:
- Method names must be the same.
- The parameter list must be different (the number is different, or the type is different, the parameters are arranged in different order, etc.).
- The return type of the method can be the same or different.
- Only the return type is not sufficient to be an overload of the method.
Implementation of method overloading:
When the method name is the same, the compiler will match the number of parameters of the calling method, parameter type, etc. to select the corresponding method, if the match fails, then the compiler error, which is called overload resolution.
9.Java Method Overloading