BCA / B.Tech 10 min read

Method Overriding in Java

What is Method Overriding in Java?

Method overriding occurs when a subclass (child class) has a method with the same name, parameters, and return type as a method in its superclass (parent class). By overriding, the subclass provides its own specific implementation of that method, replacing the behavior inherited from the parent. This is a fundamental concept for achieving run-time polymorphism (or dynamic binding).

Rules for Method Overriding:
  • The method name, parameter list, and return type must be exactly the same (or a covariant return type for objects).
  • The method must be inherited. Therefore, there must be an IS-A (inheritance) relationship between the classes.
  • The access modifier of the overriding method in the subclass cannot be more restrictive than the overridden method in the superclass (e.g., you cannot override a `public` method with a `private` one).
  • You cannot override `final` or `static` methods.

Example of Method Overriding:

The @Override annotation is not mandatory, but it is highly recommended. It tells the compiler you intend to override a method, and the compiler will produce an error if you fail to do so correctly (e.g., due to a typo in the method name).


// Superclass
class Vehicle {
    void run() {
        System.out.println("Vehicle is moving");
    }
}

// Subclass
class Bicycle extends Vehicle {
    // Overriding the run method of the Vehicle class
    @Override
    void run() {
        System.out.println("Bicycle is moving safely on two wheels");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle myVehicle = new Bicycle(); // A Vehicle reference pointing to a Bicycle object
        myVehicle.run(); // At runtime, Java calls the overridden method from the Bicycle class.
    }
}
        
Output:
Bicycle is moving safely on two wheels