Method overloading example program in Java - CodeByAkram

Method overloading example program in Java


What is method overloading?

If a class have multiple methods with same name but with different parameters list, it is known as Method Overloading.
Parameters lists should differ in either,
  1. Number of parameters.
  2. Data type of parameters.
  3. Sequence of data type of parameters. 

Example:


class ArithmeticOperations{  
 public void add(int num1,int num2){
  System.out.println(num1 + num2);
 }  
  
 public int add(int num1,int num2, int num3){
  int result = num1 + num2 + num3;
  return result;
 }
   
 public static void main(String args[]){  
  ArithmeticOperations obj = new ArithmeticOperations();    
  obj.add(1,2);
  int result = obj.add(1,2,3);
  System.out.println(result);
 }
}
What is benefit of method Overloading?

Method overloading increases the readability of the program.
Example of Java API using method Overloading?

1.  "valueOf" method of String class is overloaded in Java. It returns String representation
of variable passed in it.

2.  "substring" method of String class is overloaded in Java.

3.  "println" method of PrintStream class is overloaded.

Note: Method overloading is one of the way through which java supports polymorphism. Polymorphism achieved using method overloading is known as Compile time/Static polymorphism because which method will be invoked is decided at compile time.

Example of Real time use of method Overloading?

There is a Organization where many Employee works and we need to design a system for it. In design, for getting Employee we would have a EmployeeModel something like this, 
class Employee{
 private int id;
 private String name;
 
 //Getter & Setters
}
 
class EmployeeModel{  
 
 //Get Employee by name and dob.
 public Employee getEmployee(String name, Date dob){
  //Logic for fetching Employee emp
  return emp;
 }
 
 //Get Employee by name
 public List getEmployee(String name){
  //Logic for fetching list of Employee emp
  return listEmp;
 }
 
 //Get Employee by id  
 public Employee getEmployee(int employeeId){
  //Logic for fetching Employee emp
  return emp;
 }
}

How is ambiguous overloaded method call resolved in java?

Question 1. What is the output of below program?  
public class OverloadedMethod{
 public void test(String str) {
  System.out.println("String");
 }
  
 public void test(Object obj) {
  System.out.println("Object");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: String

On what basis Compiler decides which method to invoke?
If more than one method is both accessible and applicable to a method invocation then
Java compiler uses the set of rules that the most specific method is chosen for invocation.

In our case above, call to test(null) is suitable for both the test method declared, So in this case most specific method is chosen for invocation.

Compiler check the class hierarchy of method parameter and whichever class is least general one that is the class which is encounter first in bottom up hierarchy, that method is invoked.

Compiler will found String class as the most general class in bottom up inheritance hierarchy, that is why test(String) method is invoked

Question 2. What is the output of below program? 


public class OverloadedMethod{
 public void test(String str) {
  System.out.println("String");
 }
  
 public void test(StringBuffer obj) {
  System.out.println("Object");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: Compile time error:               
     The method test(String) is ambiguous for the type OverloadedMethod
Why compiler doesn't able to resolve overloaded method call this time?

StringBuffer and String class are both at same level in Object hierarchy, So in this case Compiler will not able to resolve which method to invoke and it gives Compile time error.
Let's see one more example and we will be get this better.


Question 3. What is the output of below program?  


class A{}
 
class B extends A{}
 
class C extends B{}
 
class OverloadedMethod{
 public void test(B obj) {
  System.out.println("B");
 }
  
 public void test(C obj) {
  System.out.println("C");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: C

Output is "C" because test(null) method call maps to method which contains parameter as class which is lowest in class hierarchy.
Note: Rules that applies for evaluating method call in overloading.

  1. Widening wins over boxing eg. test(10) will call test(long) instead of test(Integer) if both are available.
  2. Widening wins over var-args eg test(byte,byte) will call test(int,int) instead of test(byte...x) method.
  3. Boxing beats var-args eg test(byte,byte) will call test(Byte,Byte) instead of test(byte...x) method.
  4. Widening of reference variable depends on inheritance tree(so, Integer cannot be widened to Long. But, Integer widened to Number because they are in same inheritance hierarchy).
  5. You cannot widen and then box. Eg. test(int) cannot call test(Long) since to call test(Long) the compiler need to convert int to Integer then Integer to Long which is not possible.
  6. You can box and then widen. Eg. An int can boxed to Integer and then widen to Object.
  7. var-args can be combined with either boxing or widening.

No comments:

Post a Comment