Hi All,

Greeting of the day!

Today we will explore method overriding and runtime polymorphism in java.

Method Overriding- This is the ability to define specific behavior (i.e Override behavior of superclass) in a method that subclass inherits from the superclass.

The overriding method has the same name, number, and type of parameters, and return type as the method that it overrides. 

So when a class inherits a method it has the option either to use the method of a superclass or change the method body as per requirement.

Below are rules we need to follow while the overriding method in java.

  • For all abstract methods that class inherits from the superclass, you need to override those methods unless the subclass is also marked as abstract, i.e abstract method must be implemented by the first concrete subclass.
  • The overriding method must have the same name, along with the same number and type of parameter as of original overridden method. 
  • The return type must be the same or subtype of type return declared by the overridden method.
  • We can override only those instance methods in a subclass that class inherits from the superclass and which are not marked as final i.e
    • For subclass in the same package, we can override those methods of superclass which are not private and final.
    • For subclass in the different packages, we can override those methods of superclass which are not marked as final and which are public or protected.
  • Static methods can not be overridden.
  • The overriding method can not throw new or broader checked exceptions than those are declared in the original overridden method. However, it can throw any new unchecked exception irrespective of the original overridden method.
Now let's explore Runtime Polymorphism

Method overriding is called Runtime Polymorphism in java because which version of the overridden method will be called is decided at run time based on the actual object instead of the reference variable type.

Let's take an example for a better understanding.

Now let's create a subclass of Vehicle class override driveVehicle()


Now let's invoke driveVehicle() using different reference variables pointing to a different instance and check the output.

Output


So here when we used the Vehicle reference variable pointing to Car instance i.e 

Vehicle carVehicle = new Car(); 
carVehicle.driveVehicle();

we notice that driveVehicle() of Car is invoked event if, at compile time we are using Vehicle reference variable. So this is called Runtime polymorphism in java.


Let me know if you have any questions.

You can refer below useful post





Thanks

Happy Learning