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
1 2 |
myMethod(int a) myMethod(String a) |
2. Parameters with different sequence of a data types
1 2 |
myMethod(int a, String b) myMethod(String a, int b) |
3. Different number of parameters
1 2 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 |
10 I am a String |
2. Parameters with different sequence of a data types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 |
Int and String String and Int |
3. Different number of parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 |
Single Argument Method Multiple Argument Method |
Must Read: Java Tutorial