Method Overriding Tutorial With Examples In JAVA

Overriding means to extend or to pass over something, especially to overlap the previous described functionality. So Method Overriding means to re-write the previous described method again of Parent Class in Sub class with different functionality.

In Method Overriding, we overrides the method of Super Class in Sub Class. The method overriding is also called Run time Polymorphism or Dynamic Binding.


Method Overriding Explanation With Example:

Before discussing Method Overriding, let us revise our concept of Inheritance. Inheritance is a phenomena in which one class extends the properties( i.e. methods and fields) of another class. It makes our programming much easier as previously defined code is reused, and we can add our own functionality.

The class which extends the properties of another class is called Sub-Class or Child-Class or Derived-Class. And the class whose methods and fields or any other property is inherited is called Super-Class or Base-Class or Parent-Class.

Why Method Overriding? Now let us understand the problem that we face without method overriding.

In the following program we have Animal and Horse classes. In Animal Class we have defined a method which prints “Animal is running”. In Horse class we have used the already defined method run() of Animal Class as shown:

Below is code of Animal class:

class Animal {

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

}

Below is the code of Horse class which extend Animal class

public class Horse extends Animal
{
public static void main(String args[]){
Horse horse = new Horse(); //Horse class object is created
horse.run();
}

}

Output:

Animal is running

Problem & Solution: But the problem here is if we have to give specific implementation to Horse Class object, that “Horse is running” then how can we do that? The answer is Method overriding! So to give specific implementation to parent class method in sub-class we need Method Overriding.

So let’s come to Method Overriding:

  • In this process when a method defined in super class the same method is defined again in sub class
  • In sub class new functionality is defined for that method which overlap the functionality defined in Parent Class. So here method is overridden.
  • In other words we can say defining and giving a new functionality to the same method in sub class which is already present in parent class is called Method Overriding.

Lets discuss the same example again using method overriding:

class Animal {

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

}

Below is the Horse class code which override run method of Animal class after extending it:

public class Horse extends Animal

{
//run() Method is overridden in Sub-Class
void run(){          
System.out.println("Horse is running");
}

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

Output:

Horse is running

Here we see method run() is defined again in sub class Horse or in other words method run() is overlapped in the child class, giving it a different functionality. So now we have given specific implementation to the child class run() method.

Important Note: Method Overriding is also called as Run time Polymorphism or Dynamic Binding. This is due to the fact that the compiler doesn’t necessarily know what type of object is being passed at compile-time.


Writing @Override Annotation Is Optional

When you override any method, it is optional but recommended in JAVA to write @Override just above the method which you are overriding. This helps JAVA compiler to know that we want to override a method here which is already present in Parent class. But in-case if it is not present the compiler will give error letting us know that there is no method like that in Parent class.

Below is the Syntax of Method Overriding using @Override

class Parent{
method(){
//Add Functionality here
}
}

class Subclass extends Parent{
@Override
method(){
//New Functionality here for method
}
}

Real life example of Method Overriding :

Lets take a real life situation where we will need Method Overriding to code in JAVA.

Consider a case, where Hospital provides no. of patients admitted in it. But number of patients varies with the different hospitals, For example Health India hospital has 1657 patients, IVY hospital has 2965 patients  and Apollo Hospital has 1631 patients.

Below is code of Hospital parent class which has one method getNumberOfPatients() and sub class HealthIndia, IVY and Apolo class which extends parent class & override its method.

class Hospital{

	int getNumberOfPatients()

	{

		return 0;

	}

}

class HealthIndia extends Hospital{

	@Override
	int getNumberOfPatients()

	{

		return 1657 ;

	}

}

class IVY extends Hospital{
	@Override
	int getNumberOfPatients()

	{

		return 2965 ;

	}

}

class Apollo extends Hospital{
	@Override
	int getNumberOfPatients()

	{

		return 1631 ;

	}

}

Below is the code of MethodOverriding class which is the main class. Here we will create object for each sub class and run getNumberOfPatients() method on those objects to get patient details of each Hospital.

public class MethodOverriding{

	public static void main(String args[]){

		HealthIndia healthIndia=new HealthIndia();

		IVY ivy=new IVY();

		Apollo apollo=new Apollo();

		int healthIndiaPatients= healthIndia.getNumberOfPatients();

		int iVYPatients= ivy.getNumberOfPatients();

		int apolloPatients= apollo.getNumberOfPatients();

		System.out.println("Health India hospital patients: "+ healthIndiaPatients);

		System.out.println("IVY hospital Patients: "+ iVYPatients);

		System.out.println("Apollo hospital Patients: " +apolloPatients);

	}

}

Output:

Health India hospital patients: 1657
IVY hospital Patients: 2965
Apollo hospital Patients: 1631

Now we have seen different hospitals are calling same method, but at run time it has to be decided which class method is called depending on which class object is calling the getNumberOfPatients() method.


Advantages of using Method Overriding:

  • Method overriding is made to achieve Dynamic Binding or Runtime polymorphism.
  • Method overriding is used to give more specific definition to the method which is already defined in the Base Class.

Rules of Method Overriding :

  • Extended class must have same name of method as in base class.
  • Method which is overridden must have same parameters.
  • Method which is to be overridden should not be declared Final and static.

Difference between Method Overloading and Method Overriding:

Method overloading:

  • Method Overloading happens at compile time.
  • Static methods can be overloaded i.e a class can have more than one static method of same name.
  • Method Overloading is done in the same class.
  • Method Overloading gives better performance.
  • In case of Method Overloading, return type of a method does not matter (means it will be same or different).

Method Overriding:

  • Method Overriding happens at run time.
  • Static methods cannot be overridden.
  • For method overriding base and child class is required. Overriding is all about giving a specific implementation to the inherited method of a super class.
  • Method Overriding gives less performance as compared to method overloading. The reason is binding of overridden method is being done at run time.
  • In case of Method Overriding, Overriding methods  have more specific return type.

Important Points:

  • Final method can’t be overridden, as final is a keyword which when applied to class prohibits it from extending in other class, when applied to method it prohibits from overriding and when applied to keyword it prohibits from getting changed.
  • Static method can’t be overridden as static method belongs to the class and not to object of that class.
  • We cannot override main method, as it is static method.

Quick Revision points:

  • Method overriding is also called as Run time Polymorphism or Dynamic Binding.
  • It increases the readability of code.
  • It helps classes to be more specific in nature.
  • Final and Static methods cannot be overridden.

Ask Your Question Or Leave A Reply

Your email address will not be published. Required fields are marked *