What is the difference between method overloading and method overriding in Java?

Java 8Object Oriented ProgrammingProgramming

Following are the notable differences between overloading and overriding.

Method Overloading

  • In method overloading a class have two or more methods in with the same name and different parameters.
  • In overloading return type could vary in both methods.
  • JVM calls the respective method based on the parameters passed to it, at the time of method call.

Example

Live Demo

public class OverloadingExample {
   public void display(){
      System.out.println("Display method");
   }
   public void display(int a){
      System.out.println("Display method "+a);
   }
   public static void main(String args[]){
      OverloadingExample obj = new OverloadingExample();
      obj.display();
      obj.display(20);
   }
}

Output

Display method
Display method 20

Method Overriding

  • In method overriding Super class and subclass have methods with same name including parameters.
  • In overriding return types should also be same.
  • JVM calls the respective method based on the object used to call the method.

Example

Live Demo

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class RuntimePolymorphism extends SuperClass {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass obj1 = new RuntimePolymorphism();
      RuntimePolymorphism obj2 = new RuntimePolymorphism();
      
      obj1.sample();
      obj2.sample();
   }
}

Output

Method of the super class
Method of the sub class
raja
Published on 08-Jan-2018 13:57:49
Advertisements