Friday, December 30, 2016

What is method overloading in java ?

Method Overloading :

If a class have multiple methods by same name but different parameters,it known as method overloading.




Advantage Of Method Overloading :

Method overloading increases  the readability of the program.

Different ways to overload the method :

There are two ways to overload the method in java :-

1) By changing number of arguments .
2)By changing the data type.

Example for changing number of arguments :

class Sum{
   void printResult(int a,int b){
          System.out.println("Result is: "+(a+b));
   }
  void printResult(int a,int b,int c){
          System.out.println("Result is: "+(a+b+c));
   }
}
class Mytest{
  public static void main(String args[]){

    Sum s=new Sum();
    s.printResult(12,2);
    s.printResult(12,2,3);
   
 }

}

Output :
Result is: 14
Result is: 17


Example for changing data type of arguments :

class Sum{
   void printResult(int a,int b){
          System.out.println("Result is: "+(a+b));
   }
  void printResult(double a,double b){
          System.out.println("Result is: "+(a+b));
   }
}
class Mytest{
  public static void main(String args[]){

    Sum s=new Sum();
    s.printResult(12.2,2.1);
    s.printResult(12,2);
   
 }

}

Output :
Result is: 14.3
Result is: 14

No comments:

Post a Comment

how to add watermark in movavi video editor | movavi watermark | how to ...

What is static keywords in java ? static keywords in java is a main topic of java.