Home > DeveloperSection > Blogs > Method overlaoding in JAVA

Method overlaoding in JAVA


Java Java 
Ratings:
2 Comment(s)
 672  View(s)
Rate this:
If a class have multiple methods by same name but different parameters it is known as method overloading.
If we have to perform only one operation , having same name of the methods increases the readability of the program. Highlighted one is the advantage of the method overloading.

Different way to overload the method:
By changing number of arguments
by changing the data type

Example of method overloading by changing the number of arguments:

  1. class Calculation{  
  2.   void sum(int a,int b){System.out.println(a+b);}  
  3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
  4.   
  5.   public static void main(String args[]){  
  6.   Calculation obj=new Calculation();  
  7.   obj.sum(10,10,10);  
  8.   obj.sum(20,20);  
  9.   
  10.   }  
  11. }  
Output:30
       40



method overloading e.g. by changing data type

By ANkita gupta on   one year ago
  1. class Calculation2{  
  2.   void sum(int a,int b){System.out.println(a+b);}  
  3.   void sum(double a,double b){System.out.println(a+b);}  
  4.   
  5.   public static void main(String args[]){  
  6.   Calculation2 obj=new Calculation2();  
  7.   obj.sum(10.5,10.5);  
  8.   obj.sum(20,20);  
  9.   
  10.   }  
  11. }  
Output:21.0
       40
Now, question arising why method overloading is not possible by changing the return type of method
  1. class Calculation3{  
  2.   int sum(int a,int b){System.out.println(a+b);}  
  3.   double sum(int a,int b){System.out.println(a+b);}  
  4.   
  5.   public static void main(String args[]){  
  6.   Calculation3 obj=new Calculation3();  
  7.   int result=obj.sum(20,20); //Compile Time Error  
  8.   
  9.   }  
  10. }  

int result=obj.sum(20,20); //Here how can java determine which sum() method should be called.

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:

  1. class Overloading1{  
  2.   public static void main(int a){  
  3.   System.out.println(a);  
  4.   }  
  5.     
  6.   public static void main(String args[]){  
  7.   System.out.println("main() method invoked");  
  8.   main(10);  
  9.   }  
  10. }  
  11. Output:main() method invoked
           10



 


Good Explaination

By Mayank Tripathi on   one year ago
Very good explaination

Don't want to miss updates? Please click the below button!

Follow MindStick