home page

Method Overriding in Java

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

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.

Advantage 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 Method Overriding

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

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

Test it Now
Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.


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 same and there is IS-A relationship between the classes, so there is method overriding.

Test it Now
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, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

Java method overriding example of bank
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism so we will learn it later.

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.


Can we override java main method?

No, because main is a static method.


What is the difference between method Overloading and Method Overriding?

There are three basic differences between the method overloading and method overriding. They are as follows:

Method Overloading Method Overriding
1) Method overloading is used to increase the readability of the program.Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2) method overloading is performed within a class.Method overriding occurs in two classes that have IS-A relationship.
3) In case of method overloading parameter must be different.In case of method overriding parameter must be same.