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

The @Override Annotation

Use @Override to explicitly mark overriding methods and catch compile-time errors if the signature doesn't match.

The @Override Annotation

You'll learn how to use @Override to make your method overrides safer and catch errors at compile-time.

When you override a method from a superclass, you're relying on the method signature matching exactly—same name, same parameters, compatible return type. But mistakes happen: a typo in the method name, a slight parameter difference, and suddenly you've accidentally created a new method instead of overriding the parent's version.

What @Override Does

The @Override annotation is a safety label you place directly above an overriding method. It tells the compiler: "I intend this method to override something from my superclass." If the compiler can't find a matching method in the parent class, it throws a compile-time error—catching your mistake immediately.

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

class Dog extends Animal {
    @Override
    public void makeSound() {  // ✓ Correct override
        System.out.println("Bark");
    }
    
    @Override
    public void makeSoud() {  // ✗ Compile error! Typo in name
        System.out.println("Bark");
    }
}

Without @Override, the typo makeSoud() would compile fine—you'd just have two methods (makeSound and makeSoud), and your override would silently fail to work.

Why It Matters

Think of @Override as a spell-checker for inheritance. It doesn't change what your code does, but it verifies your intent. If the superclass method name changes during refactoring, @Override will alert you that your override is now broken.

Key Takeaway: Always use @Override when overriding methods—it turns silent mistakes into loud compile-time errors, making your inheritance code safer and more maintainable.