- A Class has multiple methods of the same name with different parameters is called Method overloading.
- This will allow one function call to perform different tasks depending on method parameters.
- Method overloading is also known as Static Polymorphism.
- Overload the method in Java, changing number of arguments and changing the data type
- Only based on return type, overloading is not possible in Java,
- Method overloading increases the readability and reliability of the program.
Syntax
public class OverloadClass {
public static void method(int num,String text){ //Method for (int,String)
//Logic
}
public static void method(int num1,float num2){ //Method for (int,float)
//Logic
}
}
public class MainClass {
public static void main(String[] args){
OverloadClass A;
A.method(1,"String Data"); //for first Method
A.method(1,5.6f); //for second Method
}
}
Method Overloading with different data type Example Program
class MethodOverloadingExample{
public void overloadingMethod(int num,String string){
System.out.println("Method with integer and String inputs is called.");
}
public void overloadingMethod(int num1,float num2){
System.out.println("Method with integer and float inputs is called.");
}
}
class MethodOverloadingWithDifferentDataTypes{
public static void main(String[] args){
MethodOverloadingExample obj=new MethodOverloadingExample();
obj.overloadingMethod(10,"Overloading");
obj.overloadingMethod(1,5.3f);
}
}
Sample Output
Method with integer and String inputs is called.
Method with integer and float inputs is called.