Java Programming Handbook

    Method Overriding in Java

    In Java, Method Overriding is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. The overridden method in the child class must have the same method signature as the one in the parent class.

    Why Method Overriding?#

    Method Overriding is used to achieve runtime polymorphism and to provide a specific implementation for a method in a derived class that differs from its base class.

    Key Rules of Method Overriding#

    • The method in the child class must have the same name as in the parent class.
    • The method must have the same parameters as in the parent class.
    • There must be an inheritance relationship (i.e., one class must be a subclass of another).
    • The return type should be the same or covariant (subtype of the return type in the parent class).
    • The access modifier cannot be more restrictive than the method in the parent class.
    • Methods marked as final, static, or private cannot be overridden.

    Example of Method Overriding#

    // Parent class class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } // Child class class Dog extends Animal { // Overriding the makeSound method @Override void makeSound() { System.out.println("Dog barks"); } } // Main class public class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); myAnimal.makeSound(); // Calls method from Animal class Animal myDog = new Dog(); myDog.makeSound(); // Calls overridden method from Dog class } }

    Output:#

    Animal makes a sound Dog barks

    Using super in Method Overriding#

    The super keyword can be used to call the overridden method of the parent class.

    class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void makeSound() { super.makeSound(); // Calls method from parent class System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); myDog.makeSound(); } }

    Output:#

    Animal makes a sound Dog barks

    Conclusion#

    In this blog, we learned about Method Overriding in Java, its importance in achieving runtime polymorphism, and the rules associated with it. We also explored examples demonstrating overriding and how to use super to call the parent class method. In the future blogs we will also cover difference between Method Overloading and Method Overriding in Polymorphism as it is important from the interview point of view.

    Last updated on Apr 09, 2025