javascript1

Friday, 13 February 2015

Method Overloading in Java

method overloading in Java

Method Overloading is used when we have more then one mehod with same name but perform different functionality
Suppose youneed to calculate area of  square  , rectangular and eclipse then you have two option :
1.    create different function for like area1 , area 2, area 3 in order to differentiate the function .
2.    second way use method overloading and use the same method name .

Second way is more efficient because it increase the readability of the program .

 Advantage of method overloading


Method overloading increase the readability of the program

How to do method overloading


1         by changing the number of arguments
2         by changing the data type

1) Method Overloading by   arguments number


class Operation{  
  void sum(int a,int b){System.out.println(a+b);}  
  void sum(int a,int b,int c)
{

System.out.println(a+b+c);

}  
  
  public static void main(String a[]){  
  Calculation obj=new Calculation();  
  obj.sum(10,10,10);  
  obj.sum(20,20);  
  
  }  
}  

2) Method Overloading by   arguments Type


class Operation{  
  void sum(int a,int b){System.out.println(a+b);}  
  void sum(int a,float b)
{

System.out.println(a+b);

}  
  
  public static void main(String a[]){  
  Calculation obj=new Calculation();  
  obj.sum(10,10);  
  obj.sum(20,10.4);  
  
  }  
}  



No comments:

Post a Comment