Method Overriding


Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type (or subtype) as a method in its super-class, then the method in the subclass is said to override the method in the superclass. Method overriding is one of the way by which Java achieves runtime polymorphism.

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.

In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

Overriding.java (method overriding)
// A simple program to demonstrate method overriding in Java
// Driver class
class Overriding {
  public static void main( String[ ] args ) {
    // If a Parent type reference refers to a Parent object,
    // then the Parent's show() is called.
    Parent obj1 = new Parent( args[0] );
    obj1.show( );
    // If a Parent type reference refers to a Child object,
    // then the Child's show() is called.
    // This is called RUN TIME POLYMORPHISM.
    Parent obj2 = new Child( args[0], args[1] );
    obj2.show( );
  }
}
// Base class
class Parent {
  String name;
  Parent( String name ) { this.name = name; }
  void show( ) {
    System.out.println( "Show( ) of Parent (" + this.name + ")" );
  }
}
// Inherited class
class Child extends Parent {
  String name;
  Child( String pName, String cName ) {
    super( pName );
    this.name = cName;
  }
  // This method overrides Parent's show().
  @Override
  void show( ) {
    System.out.println( "Show( ) of " + super.name + "'s Child (" + this.name + ")" );
  }
}
shell> java Overriding     (parent)   (child)

      Result:




      The average person is so compartmentalized in their mind that they    
      cannot see the forest for the trees (only look at small details).