Wednesday, 6 January 2016

Method Overriding in Java


Method overriding, in object oriented programming, is a language 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.

That means if subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

Usage of Java Method Overriding

  • Method overriding is used to provide specific usage of a method that is already provided by its super class (parent class).
  • Method overriding is used for runtime polymorphism


One of the simplest example – Here A class extends B class. Both the classes have a common method void run(). B class is giving its own implementation to the run() method or in other words it is overriding the method run().

class B{
   public void run()
      System.out.println("Inside B");
class A extends B{
   public void run(){
      System.out.println("Inside A");
   public static void main( String args[]) {
      A obj = new A();;
Inside A
Advantage of method overriding: The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class(base class).

No comments :

Post a Comment