Category Archives: Method Overloading

Methods Overloading :

Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different.It is used when objects are required to perform similar tasks but using different input parameters. Method overloading increases the readability of the program.

There are two ways to overload the method :
1.By changing number of arguments
2.By changing the data type

∑  In java, Method Overloading is not possible by changing the return type of the method.
∑  
Method overloading is also known as Static Polymorphism.

class Display {
void Sum(int a, int b){
System.out.println(a+b);}
void sum(int a, int b, int c){   //Method Overloading by changing the no. of arguments
System.out.println(a+b+c);}
void sum(double a,double b){  // Method Overloading by changing data type of arguments
System.out.println(a+b);}

public static void main(String args[]){
Display S = new Display();
S.sum(20,30);
S.sum(10+20+30);
S.sum(5.5,5.5);
}
}

Output :

50
60
11.0

∑ In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity and it will give compile time error.
∑ We can overload the main() method.

class OverloadMain{
public static void main(int a){
System.out.println(a);
}

public static void main(String args[]){
System.out.println("main() method invoked");
main(20);
}
}

Output :

main() method invoked
20