Course contentsShow
← Java
Lesson 414 of 2,87010. Inheritance FundamentalsFree lesson

What Is Method Overriding?

Learn how subclasses can replace superclass method implementations while maintaining the same signature.

What Is Method Overriding?

You'll learn what method overriding is and why subclasses sometimes need to replace inherited methods with their own versions.

The Core Idea

When a subclass inherits a method from its superclass, it doesn't always want to keep the exact same behavior. Method overriding lets the subclass provide its own implementation of an inherited method while keeping the same method signature (name, parameters, and return type).

Think of it like a family recipe: your parent teaches you how to make spaghetti sauce, but when you grow up, you might make it your own way—perhaps adding different spices. You're still making "spaghetti sauce" (same method name), but your version works differently.

How It Works

The subclass declares a method with the exact same signature as one in the superclass. When you call that method on a subclass instance, Java runs the subclass's version, not the superclass's version. The subclass method replaces the inherited one.

class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    void makeSound() {  // Overriding Animal's makeSound()
        System.out.println("Woof!");
    }
}

When you create a Dog and call makeSound(), you get "Woof!"—not "Some generic sound." The Dog class has overridden the inherited method to provide dog-specific behavior.

Why Override?

Subclasses often need specialized behavior. A Dog doesn't make "some generic sound"—it barks. Overriding allows each subclass to customize inherited methods while maintaining a consistent interface across the class hierarchy.

Key Takeaway: Method overriding allows a subclass to replace an inherited method's implementation by declaring a method with the same signature, providing specialized behavior while maintaining type compatibility.