Method Overriding or Dynamic Polymorphism in Java

By | September 26, 2018

In this post of Method Overriding or Dynamic Polymorphism in Java you will learn about Method Overriding or Dynamic Polymorphism in detail.

In a parent-child relation between classes, if a method in sub class has same signature as the parent class method then the method is said to be overridden by the sub class and this kind of process is called method overriding in Java.

Example of Method overriding in Java

Output of the program:

It can be noticed here that when displayValue() is invoked on an object of class ChildClass, the overridden displayValue() method of the child class is called. 

You must note that in the case of parent-child relationship if both classes have the method with same name and signature then only it is known as method overriding, otherwise it is considered  as method overloading only.

Benefit of method overriding in Java

Method overriding allows java to support run-time polymorphism which in turn helps in writing more robust code and code reuse.

Method overriding helps us in hierarchical ordering where we can move from general to specific.

If you use the same above example to demonstrate run time Polymorphism here.

Output of the program: 

It can be noticed here that initially parent object(object of ParentClass) calls displayValue() method of parent class(ParentClass), later at run time the reference is changed and the parent is assigned the reference of child class(ChildClass). Now, when the displayValue() method is called on the parent object, it calls the overridden method of the class Child(ChildClass). 

Some of the key points about method overriding

  • If method in the sub-class has the same name and signature as the parent class method then only it is called method overriding otherwise it is method overloading.
  • Method overriding allows java to support run-time polymorphism.
  • The Method overriding helps us in hierarchical ordering where you can move from general to specific implementation. In super class a method can have a general implementation whereas the sub classes provide the more specific implementation by overriding the parent class method.
  • If a method is declared as final in parent class then it can not be overridden by sub classes.
  • If a method is declared as abstract in the parent class then the sub class has to provide implementation for those inherited abstract methods

That’s all about Method Overriding or Dynamic Polymorphism in Java
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

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