Tuesday 22 November 2016

METHOD OVERLOADING IN JAVA

When a Java Program contains more than one method with same name ,but with different number and type of parameters ,then it is said to be overloaded .
Suppose we have a one function with name sum that is sum(),the the sum function can be overloaded by using different number and type of
arguments or parameters as:
void sum (int a,int b)
 {
     System.out.println(a+b);
 }    

void sum (int a,int b)
 {
    System.out.println(a+b);

 }   

void sum (float a,float b)
 {
     System.out.println(a+b);
 }   
The main advantage of using Method overloading is that it increases the readability and understanding of Program.It is not possible to overload the Function by changing the return type of a function as it is possible in C++ programming as it leads to the unambiguous situations in Java.It is also possible to have any number of main () methods in Java Program, thus main () method can also be overloaded.
Example of Overloading Function in java:
  1. class Function{  
  2.   void sum(int a,int b)
  3. {
  4. System.out.println(a+b);
  5. }  
  6.   void sum(int a,int b,int c)
  7. {
  8. System.out.println(a+b+c);
  9. }    
  public static void main(String args[])
{  
 Function obj=new Function();  
  obj.sum(10,10,10);  
  obj.sum(20,20);  
  
  }  

No comments:

Post a Comment