What is method overloading?
The requirements for method overloading are two identical: the same method name in the same class, and the parameter list is different. Other parts of the method, such as the method return value type, modifier, and so on, have no relation to the method overload.
Why do you use method overloading?
The purpose of overloading is to make it easier for programmers to invoke methods. For example, System.out.println () This function is used to output, when the output is an integer is used in this method, when the output of a string is still used this method. The matching method is automatically found based on the different parameters passed in.
Method overloading is a compile-time polymorphism that determines the method signature at compile time.
1 Importjava.util.ArrayList;2 Importjava.util.LinkedList;3 Importjava.util.List;4 Importjava.util.concurrent.CopyOnWriteArrayList;5 6 Public classTestoverloadmethod {7 8 Public voidTestoverload (arraylist<string>arrayList) {9System.out.println ("ArrayList");Ten } One A Public voidTestoverload (linkedlist<string>LinkedList) { -System.out.println ("LinkedList"); - } the - Public voidTestoverload (list<string>list) { -SYSTEM.OUT.PRINTLN ("list"); - } + - Public Static voidMain (string[] args) { +list<list<string>> lists =NewArraylist<list<string>>(); ALists.add (NewArraylist<string>()); atLists.add (NewLinkedlist<string>()); -Lists.add (NewCopyonwritearraylist<string>()); - -Testoverloadmethod obj =NewTestoverloadmethod (); - for(list<string>list:lists) { - obj.testoverload (list); in } - } to +}
Results:
1 List 2 List 3 List
Although the runtime determines which method to call, the method signature is determined at compile time. Because the compiler sees Obj.testoverload (list), the declaration type of the list at execution time is list<string>, so the method signature generated by this call is Testoverload (List list), This method is called through reflection at run time.
Resources
Java method Overloading rules
Why do I need to use overloaded
A little bit of thinking about why static methods cannot be rewritten and some pits of overload.
Java Method Overloading