Java method overloading allows different methods with the same name, but different signatures. Where the signature can be different by the number of input parameters or type of passing parameters or both.
See Also:
- Java: Method Signature
- Java: Method Overriding
- Java: Method Overloading Vs Method Overriding
- Exception handling with method overriding
Advantage of method Overloading
- Don’t need to remember so many method names.
Points to remember about Method Overloading
- Method Overloading is related to the concept of compile-time (or static) polymorphism.
- Method Overloading possible on the same class.
- Method Overloading doesn’t consider the return type of method. If two method signature is the same and only differ in return type then the compiler will show as a duplicate method.
- Method Overloading can overload static methods but not based on keyword static only.
- Method Overloading can also be done for the main() method.
- Java language doesn’t support user-defined operator loading but internally supports operator overloading for example : (+) for concatenation.
Note: (Java 8+)If both methods have the same parameter types, but different return type, then it is not possible.
Ways to do Method Overloading
Method overloading is possible by:
- Change the number of parameters in methods.
- Change data types of the parameters in methods.
- Change Order of the parameters of methods.
How to determine parameter matching in Overloading with different Types?
Parameter matching determines when parameter type is different but to higher type(in terms of range) in the same family.
For Example: suppose passing argument type is int, then check for an overloaded method of type int if not found then check for the data type of higher in the same family( long type if still not found then check for the float data type).
public class Demo { //overloaded methods public void show(int x) { System.out.println("In int " + x); } public void show(String s) { System.out.println("In String " + s); } public void show(byte b) { System.out.println("In byte " + b); } public static void main(String[] args) { byte a = 25; Demo obj = new Demo(); // If will call method with by argument obj.show(a); obj.show("Facing Issues On IT "); // String obj.show(250); // Int /* * Since method with char type is not available, * so the data type higher * than char in same family is int */ obj.show('A'); /* * Since method with float data type is * not available and so it's higher * data type, so at this step their will * be an compile time error. */ // obj.show(7.5); } }
Output
In byte 25
In String Facing Issues On IT
In int 250
In int 65