Method overriding in Java

A subclass having a method with the same name as that of its parent class, such that it has exactly the same arguments as that of the parent method, then it is known as method overriding.

Method overriding is also called as runtime polymorphism.

Note that method overriding takes place only when inheritance is involved.

Let’s check out a simple example on method overriding below:

The above example clearly portrays what we said. The two subclasses, namely RajComics and DiamondComics have their own specific read method implementations. So in other words, both these classes have overridden the default method implementation of it’s parent or super class.

In case of method overriding, the method signature must be exactly the same except for the exception part that is thrown. This means that –

We can’t override a public method and make it protected. No.

However, the exception part of the method signatures can be different in a way such that “the exception may not be thrown at all by the overriding method or if thrown, it should not be higher in hierarchy than that of the overridden method”.

Before you wrap up with this topic, don’t miss out some nice interview questions on Polymorphism.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.