Method Overriding in Java

When parent class and child class contains method with same method signature but different implementation then at runtime child class method will be executed. It is called method overriding. Let's understand method overriding with following example.

In this example child class inherit parent class. In Inheritance we know that child class inherit parent class properties so when we call m1() method either by parent class reference object or child class reference object, JVM at runtime execute child class m1() method.

Rules for overriding- 

1. both class should have IS- A Relationship

2. method name and arguments(including order) must be same

3. Return type of both method must be same or return type of parent class method must be parent of return type of child class method i.e. co-variant return type.

4. Parent class method can't have private access modifier because private method won't be available for child class.

5. If child class method throws checked Exception then parent class method should also throws same checked Exception or parent of that Exception of child class method.

6. Scope of access modifier in child class must not be reduced that means if parent class method have public access modifier then child class method can only have public modifier or if parent class method have protected access modifier then child class method can have protected or public modifier.

7. Static method can't be overridden.

0 comments:

Post a Comment