Method Overriding and Overloading in Java

"Strive to be of Value, Not to be a Success"
--Albert Einstein
Method Overriding is when a subclass redefines/rewrites an inherited method. Same method name and arguments are available in parent(base) and child(sub) class, but their implementation will differ. Calling the method with a sub-class variable will execute the sub-class's method. Sample program below to demonstrate overriding.

Method Overloading is when we have two or more methods in a class with same name but different arguments. In the program below I added overloaded methods in base and sub-class.

 package com.examples;  
 import java.util.Date;  
 class India {  
      void ride() {  
           System.out.println("Riding in India..");  
      }  
      void load() {  
           System.out.println("Loading in India");  
      }  
 }  
 class Bangalore extends India {  
      @Override //Good practice  
      void ride() {//Overriding method  
           System.out.println("Riding in Bangalore...");  
      }  
      void load(Date n) { //Overloading here  
           System.out.println("Loading in Bangalore: " + n);  
      }  
 }  
 public class OverrideOverload {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Bangalore ob = new Bangalore();  
           ob.ride();  
           ob.load();  
           ob.load(new Date());  
      }  
 }  

Output:
 Riding in Bangalore...  
 Loading in India  
 Loading in Bangalore: Thu Feb 27 01:24:58 IST 2014  

Note: Annotating an overriding method with @Override is a good practice. This properly indicates the compiler about overriding and helps detect overloading or other mistakes, for e.g. if somebody else is reviewing the code.

No comments:

Post a Comment