Tuesday, November 18, 2014

Difference between method overloading and method overriding

Method overloading in Java occurs when two or more methods in the same class have the exact same name but different parameters.  Overloading is a compile time (static) phenomenon because the compiler is aware of exactly which method you are calling based on the number/type of parameters.
 
class Animal{
       void test(){
              System.out.println("Inside Animal class with no aruguments");
       }
      
       void test(int a){
              System.out.println("Inside Animal class with int aruguments");
       }
}

public class TestMain {
       public static void main(String[] args) {
              Animal a = new Animal();
              a.test();
              a.test(5);
       }

Output:
Inside Animal class with no aruguments
Inside Animal class with int aruguments

In this case, the compiler knows exactly which “test” method we are calling, based on the number/type of parameters.

Overriding methods is completely different from overloading methods. If a derived class requires a different definition for an inherited method, then that method can be redefined in the derived class. This would be considered overriding. An overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method. Overriding is an example of dynamic (run-time) polymorphism. This is due to the fact that the compiler doesn't necessarily know what type of object is being passed in at compile-time.

class Animal{
       void test(){
              System.out.println("Inside Animal class with no aruguments");
       }
      
       void test(int a){
              System.out.println("Inside Animal class with int aruguments");
       }
}

class Dog extends Animal{
       void test(){
              System.out.println("Inside Dog class with no arguments");
       }
}

public class TestMain {
       public static void main(String[] args) {
              Animal a = new Dog();
              a.test();
              a.test(5);
       }

}

Output:
Inside Dog class with no aruguments
Inside Animal class with int aruguments

Here, method dispatching is performed in two steps:
  • The first one is done at compile time with the static information available, the compiler will emit a call for the signature that matches best your current method parameters among the list of overloaded methods in the declared type of the object the method is invoked upon.
  • The second step is performed at run time, given the method signature that should be called (previous step), the JVM will dispatch it to the most concrete overridden version in the actual type of receiver object.