Java allows multiple methods to be defined in a class, as long as the list of arguments is different. If the same class contains two or more than two methods with the same method name, but the formal parameter list is different, it is called the method overload.
/*overloads with different parameter types*/ Public classOverload {//the two test () methods are defined below, but the formal parameter lists of the methods are different//The system can differentiate this method, which is called method overloading Public voidTest () {System.out.println ("No Parameters!" "); } Public voidTest (String A) {System.out.println ("Overloaded Test () method:" +A); } Public Static voidMain (string[] args) {overload ol=Newoverload (); Ol.test (); Ol.test ("Yes"); }}
The output is:
No Parameters!
Overloaded Test () method: Yes
/*overloads with different number of arguments*/ Public classNumoverload { Public voidTest () {System.out.println ("Only one string argument to the test method!" "); } /*There is already a test () method, there is only one string parameter in the test () method where the number of variable arguments does not include the form of a string argument*/ Public voidTest (string...books) {System.out.println (* * * * parameter variable Test () method * * * * * *); } Public Static voidMain (string[] args) {numoverload nol=Newnumoverload (); //The following two calls will execute the second Test () methodnol.test (); Nol.test ("AA", "BB"); //The First Test () method is called belowNol.test ("AA"); //a second Test () method is called belowNol.test (Newstring[]{"AA"}); }}
Output Result:
Only one string argument to the test method!
Parameter variable Test () method * * * *
Parameter variable Test () method * * * *
Parameter variable Test () method * * * *
Note: It is generally not recommended to overload the variable number of parameter parameters, because in the above example, if you need to call the test (string ... books) method, and only want to pass in a string parameter, you can take the form of the incoming string group. If you simply pass in a string, there will be confusion with 2 of methods.
Java Method overloading