1. What is Method Overloading?
Method Overloading is a feature in Java
where multiple methods have the same method name and same number of parameters,arguments but different parameters , different data type in the same class.
It is the one of the Polymorphism called the Compile-Time Polymorphism
The methods differ by:
Number of parameters
Type of parameters
Order of parameters
Example
public class Sample{
public static void main(String[]args){
Sample casio = new Sample();
casio.add(10,20);
casio.add(10,20,30);
casio.add();
}
public void add(int no1,int no2){
System.out.println("2 arguments");
}
public void add(){
System.out.println("0 arguments method");
}
public void add(int no1,int no2,int no3){
System.out.println("3 arguments");
}
}
Output
2.Rules of Method Overloading
Not Change the Number of Parameters
class SumExample {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
SumExample obj = new SumExample();
System.out.println(obj.sum(10, 20));
System.out.println(obj.sum(10, 20, 30));
}
}
Output
Not Change the Data Type of Parameters
class PrintExample {
void print(int a) {
System.out.println("Integer: " + a);
}
void print(String a) {
System.out.println("String: " + a);
}
public static void main(String[] args) {
PrintExample obj = new PrintExample();
obj.print(100);
obj.print("Java");
}
}
Output
Not Change the Order of Parameters
class ShowExample {
void show(int a, String b) {
System.out.println(a + " " + b);
}
void show(String b, int a) {
System.out.println(b + " " + a);
}
public static void main(String[] args) {
ShowExample obj = new ShowExample();
obj.show(10, "Java");
obj.show("Hello", 20);
}
}
Output
Changing only the return type is NOT allowed in Java.
Example
class Calculator {
int multiply(int a, int b){
return a * b;
}
int multiply(int a, int b, int c){
return a * b * c;
}
double multiply(double a, double b){
return a * b;
}
public static void main(String[] args){
Calculator obj = new Calculator();
System.out.println(obj.multiply(5, 4));
System.out.println(obj.multiply(2, 3, 4));
System.out.println(obj.multiply(2.5, 4.0));
}
}
Output
3. Step-by-Step Execution
Program starts from the main() method
Object of the class is created
Method is called using the object
Java compares the arguments with method parameters
The correct overloaded method runs
Output is displayed
4.Advantage Of Method OverLoading
Keep code clean and readable
Use the same method name for similar operations
Avoid creating many method names
Make programs easier to maintain
5. Simple Real-Life Idea
Think of a mobile phone camera:
Same button → Camera
Different modes:
Photo
Video
Portrait
Same name, different behavior depending on input.