DEV Community

Harini
Harini

Posted on

Method Overriding in Java

Method Overriding in Java

  • Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
  • When a method in a subclass has the same name, same parameters, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
  • Method overriding is one of the way by which java achieve Run Time Polymorphism.

Usage of Java Method Overriding

  • Method overriding is used for achieving run-time polymorphism.
  • Method overriding is used for writing specific definition of a subclass method (this method is known as the overridden method).

Rules for Overriding

  • Method name must be the same
  • Parameters must be the same
  • Return type must be the same (or compatible)
  • It must be in a parent-child (inheritance) relationship
  • Java picks which method to run at run time, based on the actual object type, not just the reference variable type.

Example

class Vehicle{  
    void run(){
        System.out.println("Vehicle is running");
    }  
}  

class Bike extends Vehicle{  
    void run(){
        System.out.println("Bike is running safely");
    }  

    public static void main(String args[]){  
        Bike obj = new Bike();  
        obj.run(); 
    }  
}  
Enter fullscreen mode Exit fullscreen mode

Output
Bike is running safely

Top comments (0)