< Java Tutorial

Java method overriding

← Previous Next →


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

In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

Method overriding is used to provide specific implementation of a method that is already provided by its super class.
Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is sa>me and there is IS-A relationship between the classes, so there is method overriding.

class Vehicle
{
    void run()
    {
        System.out.println("Vehicle is running");
    }
}

class Bike2 extends Vehicle
{ 
    void run()
    {
        System.out.println("Bike is running safely");
    }

    public static void main(String args[])
    {
        Bike2 obj = new Bike2(); 
        obj.run();
    }
}

Output:

Bike is running safely

Real example of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI and ICICI banks could provide 8% and 7%  rate of interest.

class Bank
{  
    int getRateOfInterest() 
    {
        return 0;
    }  
}  
  
class SBI extends Bank
{  
    int getRateOfInterest()
    {
        return 8;
    }  
}  
  
class ICICI extends Bank
{  
    int getRateOfInterest()
    {
        return 7;
    }  
}  
  
class Test2
{  
    public static void main(String args[])
    {  
        SBI s=new SBI();  
        ICICI i=new ICICI();  
        
        System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
        System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
    }  
}  

Output:

SBI Rate of Interest: 8
ICICI Rate of Interest: 7

← Previous Next →