Method Overloading In Java
A class having multiple methods with same name but different parameters is called Method Overloading
There are three ways to overload a method.
1. Parameters with different data types
myMethod(int a) myMethod(String a)
2. Parameters with different sequence of a data types
myMethod(int a, String b) myMethod(String a, int b)
3. Different number of parameters
myMethod(int a) myMethod(int a, int b)
Earlier we have seen method signature. At compile time, Java knows which method to invoke by checking the method signatures. So this is called compile time polymorphism or static binding.
Let’s see some practical example for better understanding.
1. Parameters with different data types
package methodOverloadingDiffDataTypes; public class MethodOverloadingDiffDataTypes { public void methodOne(int a){ System.out.println(a); } public void methodOne(String a) { System.out.println(a); } public static void main(String[] args) { MethodOverloadingDiffDataTypes obj = new MethodOverloadingDiffDataTypes(); obj.methodOne(10); obj.methodOne("I am a String"); } }
Output:
10 I am a String
2. Parameters with different sequence of a data types
package methodOverloadingDiffSequenceDataTypes; public class MethodOverloadingDiffSeqDataTypes { public void methodOne(int a, String b){ System.out.println(b); } public void methodOne(String a, int b) { System.out.println(a); } public static void main(String[] args) { MethodOverloadingDiffSeqDataTypes obj = new MethodOverloadingDiffSeqDataTypes(); obj.methodOne(1, "Int and String"); obj.methodOne("String and Int", 2); } }
Output:
Int and String String and Int
3. Different number of parameters
package methodOverloadingDiffNumberParameters; public class MethodOverloadingDiffParameters { public void methodOne(int a){ System.out.println("Single Argument Method"); } public void methodOne(int a, int b) { System.out.println("Multiple Argument Method"); } public static void main(String[] args) { MethodOverloadingDiffParameters obj = new MethodOverloadingDiffParameters(); obj.methodOne(10); obj.methodOne(10, 20); } }
Output:
Single Argument Method Multiple Argument Method
Must Read: Java Tutorial