Method Overriding in Java

In child-parent relationships of classes when a child class is not satisfied with the method implementation present in the parent class or when child class wants to give their own definition to the method, they can rewrite the same method in child class. So declaring a method with the same signature, present in parent class into child class is called as method Overriding.

It is also known as runtime polymorphism, dynamic binding. It is the process in which a call to an overridden method is resolved at runtime.

Let’s take an example to understand this concept.

Method Overriding in Java

Example of method overriding in Java

class indianbank{  
int getRateOfInterest(){return 0;}  
class SBI extends indianbank{  
int getRateOfInterest(){return 8;}  
class ICICI extends indianbank{  
int getRateOfInterest(){return 7;}  
class AXIS extends indianbank{  
int getRateOfInterest(){return 9;}  
class Test{  
public static void main(String args[]){  
SBI s=new SBI();  
ICICI i=new ICICI();  
AXIS a=new AXIS();  
System.out.println("SBI Rate of "+s.getRateOfInterest());  
System.out.println("ICICI Rate of  "+i.getRateOfInterest());  
System.out.println("AXIS Rate of : "+a.getRateOfInterest());  
Example Output

Advantages of Method overriding

The main advantage of method overriding is that a class can give its own specific implementation of the method without modifying the parent class method code.

This is very useful when a class has many child classes. If the child class is satisfied with the parent class method code they can use, and if not they can rewrite the method in that class and change the behavior without touching parent class.