Method overloading means that multiple methods with the same name but different parameters can be defined in a class. When called, the corresponding method will be selected according to the unused parameter table.
for example
public class Test { void max(int a,int b) { System.out.println(a>b ? a:b); } void max(double a,double b) { System.out.println(a>b ? a:b); } public static void main(String[] args) { Test t = new Test(); t.max(3,4); t.max(3.0,4.4); } }The output is:
4 4.4
The constructor can also be overloaded
Let's take a look at another example
class ChongZai{ public void a(int a); public void a(Strting a); public void a(int a,int b);} As mentioned above, it is an overload and the overload must meet the following conditions:
1. Must be the same class
2. The method name (can also be called a function)
3. The parameter types are different or the number of parameters is different
At the same time, I will also tell LZ about the function of overloading. Let’s talk about the above example.
ChongZai cz =new ChongZai();cz.a(1); //Call a(int a);cz.a("Passed Parameter"); //Call a(String a)cz.a(1,2); //Call a(int a,int b)The above has already mentioned which method to call. This method is used by the program to determine which method to call according to the parameters you entered.
Let’s talk about the function of overloading, for example, if you make a game, you may have multiple people who finish the game. If the number of people is not sure how many people are, then you can use overloading.
For example, at most 3 people, you can define 3 parameters
public void a(String a);public void a(String a,String b);public void a(String a,String b,String c);
Two people, then you call the method with 2 parameters, 3 people, you call the method with 3 parameters, and how to call it has been explained above