If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
The benefit of overriding is: ability to define a behaviour that’s specific to the subclass type which means a subclass can implement a parent class method based on its requirement.
Rules for Java Method Overriding
- method must have same name as in the parent class
- method must have same parameter as in the parent class.
- must be IS-A relationship (inheritance).
Example of method overriding
class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike2 extends Vehicle{ void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike2 obj = new Bike2(); obj.run(); } Output:Bike is running safely
Using the super keyword:
When invoking a superclass version of an overridden method the super keyword is used.
class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class } } output: Animals can move Dogs can walk and run