What is Method Overriding in Java?


We have seen method overloading, which is an example of compile time polymorphism in one of our articles. Now, let us look at method overriding which is an example of dynamic or run time polymorphism.
What is Method Overriding? The answer to this question is pretty straight. Declaring a method in the child class which is already present in the parent class is known as method overriding. Let us understand this with the help of an example.


Example

Output

Let us look at the output of the above example code.

Method Overriding in java
Fig.1- Method Overriding

In this example we have taken two classes namely, Parent and Child. The class Child is the sub-class of the class Parent. As you can notice, both the classes have a common method display(). The Child class is overriding the display() method given in the Parent class.

Rules for Method Overriding

  • Access Modifiers: The access modifier for an overriding method can allow more, but not less access than the overridden method. Let us modify our previous example to understand that.

Output

Let us look at the output of the above example code.

Method overriding access modifiers
Fig.2- Method Overriding - Access Modifiers

Let us modify the access modifier in the above case and check again.


Output

Let us look at the output of the above example code.

Method overriding rules
Fig.3- Method Overriding - Access Modifiers Rules

Voila! We see the output again. This is exactly what this rule implies. You can learn more about the access modifiers from here.

  • If you don`t want a method to be overridden, declare it as final. Much like the final keyword, static and private methods cannot be overridden. All these keyword signifies the availability of the method to the local class in which they are defined.
  • The argument list of child class should match with that of parent class.

Super keyword in Method Overriding

The super keyword is used for calling the parent class method or constructor. Let us see an example to understand the use of super keyword in method overriding.


Output

Let us look at the output of the above example code.

Method Overriding super keyword
Fig.4- Method Overriding - super keyword

Here in this example, super.display() calls the display() method of the base class, while super() calls the constructor of the base class. So basically, with the help of super we can call the overridden methods.

Summary

In this article we walked through the concept of method overriding. The main advantage of method overriding is that a child class can give its own implementation to an inherited method without the worrying of changing the parent class. There are certain rules which need to be followed while implying the concept of method overriding. With the super keyword, we can call the overridden methods.

Read More

Author : Satyam Kumar -



You will also like: