PREV NEXT
Java Method Overloading:
- If a class contains two or more methods with the same name, it is called JAVA method overloading.
- It is used to achieve static polymorphism.
- Binding of the method to its method call, is done in the compile time itself and hence it is called static binding or early binding.
- The overloaded methods can differ by the number of arguments or argument type or sequence of the arguments.
- The overloading method can be present in the same class or in subclasses of current class also.
The difference should be only in the types and count of parameters, not in the method return types.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Addition { public void add(int a, int b) { int c =a+b; System.out.println(“Addition of the 2 numbers is:”+c); } public void add(float a, float b) { float c =a+b; System.out.println(“Addition of the 2 numbers is:”+c); } public void add(int a, int b, int c) { int x =a+b+c; System.out.println(“Addition of the 3 numbers is:”+x); } } class MainClass { public static void main(String args[]) { Addition obj = new Addition(); obj.add(4,8); //invokes add(), whose arguments are integers obj.add(5.2, 4.0); // invokes add(), whose arguments are float obj.add(4,8,3); //invokes add(), which has 3 integers as arguments } } |
Output:
Addition of the 2 numbers is:12 Addition of the 2 numbers is:9.2 Addition of the 3 numbers is:15 |