Method Overloading in Java allows you to have two or more methods with same method name but with the difference in the parameters.
There are three possible cases in which we achieve it
- Difference in the number of parameters
- Difference in the datatypes
- Difference in the sequence of parameters.
Case 1: Difference in the number of parameters
Here the Overloading class has 3 disp() methods, here the number of parameters passed is different
class Overloading { public void disp() { System.out.println("Inside First disp method"); } public void disp(String val) { System.out.println("Inside Second disp method, value is: "+val); } public void disp(String val1,String val2) { System.out.println("Inside Third disp method, values are : "+val1+","+val2); } } public class MethodOverloadingExample { public static void main (String args[]) { Overloading oo = new Overloading(); oo.disp(); //Calls the first disp method oo.disp("Java Interview"); //Calls the second disp method oo.disp("JavaInterview", "Point"); //Calls the third disp method } }
Output
Inside First disp method Inside Second disp method, value is: Java Interview Inside Third disp method, values are : JavaInterview,Point
Case 2: Difference in the datatypes
Here the Overloading class has 2 disp() methods with the same number of parameters but datatypes of the parameters will be different
class Overloading { public void disp(int val1,int val2) { int val=val1+val2; System.out.println("Inside First disp method, values is : "+val); } public void disp(String val1,String val2) { System.out.println("Inside Third disp method, values are : "+val1+","+val2); } } public class MethodOverloadingExample { public static void main (String args[]) { Overloading oo = new Overloading(); oo.disp(1,2); //Calls the first disp method oo.disp("JavaInterview", "Point"); //Calls the second disp method } }
Output
Inside First disp method, value is: 3 Inside Second disp method, values are : JavaInterview,Point
Case 3 : Difference in the sequence of parameters
Here the Overloading class has 2 disp() methods with the same number of parameters and same datatypes but the sequence will be different.
class Overloading { public void disp(int val1,String val2) { int val=val1+val2; System.out.println("Inside First disp method, values are : "+val1+","+val2); } public void disp(String val1,int val2) { System.out.println("Inside Third disp method, values are : "+val1+","+val2); } } public class MethodOverloadingExample { public static void main (String args[]) { Overloading oo = new Overloading(); oo.disp(456,"JavaInterviewPoint"); //Calls the first disp method oo.disp("JavaInterviewPoint",123); //Calls the second disp method } }
Output
Inside First disp method, value are : 456,JavaInterviewPoint Inside Second disp method, values are : JavaInterviewPoint,123
Leave a Reply