Font Awesome Icons

Tutorial

Method Overloading in Java

Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. Method overloading increases the readability of the program.

 

Ways to overload the method in java

 

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

By changing the number of arguments

 

public class Sum

{       

public void sum(int x, int y)

{        

System.out.println(x+y);    

}

            public void sum(int x, int y, int z)

{      

System.out.println(x+y+z);    

}      

public static void main(String args[])

{         

Sum s = new Sum();       

s.sum(5, 7);       

s.sum(5,7,9);    

}

}

By changing the data type of arguments

 

class Sum2

{   

void add(int a, int b)

{  

System.out.println(a+b);   

}  

void add(double a, double b)

{  

System.out.println(a+b);   

}  

}  

public class OL

{  

public static void main(String[] args)

{   

Sum2 a=new Sum2(); 

a.add(5,8); 

a.add(3.5,8.5);

}

}

Hi, Welcome to etechvidya