Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 7

Overriding an inherited method

@Override, and the rules that separate overriding from an accidental overload

20m55 XP
→→→

What you'll be able to do

  • Replace a parent's method implementation in a child class
  • State the five rules a valid override must satisfy
  • Explain what `@Override` actually does for you
  • Spot an accidental overload that was meant to be an override
1

Method Overriding

The child has a better answer

`Animal.sound()` can only say 'makes a sound'. A Dog knows better — and it does not need a new method name to say so.

Method overriding = a subclass declares a method with the *same signature* as one it inherited, and provides a different body. From then on, that object uses the child's version. Why this matters so much: the *caller does not change*. Everyone keeps calling sound(). The behaviour that runs depends on what the object actually is. That single idea is what makes polymorphism (Module 8), abstract classes (Module 10) and interfaces (Module 11) work — all three are built on overriding.

The same job description, different specialists

A hospital's job description says every doctor must be able to treat(patient). The cardiologist, the dentist and the paediatrician all keep that exact job title — and each does something completely different. Reception never needs to know which one it is: it just says 'treat this patient'. Overriding is the specialist rewriting the *how* while keeping the *what*.

A correct override

Main.java
1class Animal {
2 void sound() {
3 System.out.println("This animal makes a sound");
4 }
5}
6
7class Dog extends Animal {
8 @Override
9 void sound() {
10 System.out.println("Woof");
11 }
12}
void sound() {
The parent's version — a sensible generic default. Note there is nothing special about it: any inherited, visible, non-final, non-static method can be overridden.
@Override
An annotation: a note to the compiler. It says 'I believe I am overriding something'. If the signature does not match a parent method, compilation fails immediately — which is exactly what you want.
void sound() {
Identical name, identical parameter list (none), compatible return type. Same signature = override. Change the parameters and it becomes a *different* method (an overload) instead.
System.out.println("Woof");
The new behaviour. The parent's body is not executed at all — unless you explicitly call super.sound().
Three animals, one method name

Add a `Cow` that overrides `sound()` with 'Moo', then make a Cow speak. You never invent a new method name.

Output
Press Run to execute this example.

Always write @Override

It is optional for the compiler but priceless for you. Misspell sound as Sound, or write sound(String s) by accident, and without the annotation Java happily creates a brand-new method that nobody ever calls — a silent bug that can take hours to find. With @Override it is a compile error in one second.

Prove it — coding challenges

2

Overriding Rules

The rules the compiler checks

'Same method' is a precise idea in Java, not a feeling. Five rules define it.

Rules for a valid override

RuleMust beIf you break it
Method nameexactly the sameyou created an unrelated method
Parameter listexactly the same (types and order)you created an overload, not an override
Return typesame, or a subclass of it (covariant)compile error: incompatible return type
Access levelsame or widercompile error: attempting to assign weaker access privileges
Target methodnot static, not final, not privateyou hide or shadow it instead of overriding it

Notice the asymmetry in rule 4: a `protected` method may be overridden as `public` (widening is fine), but a `public` method can never become `protected` — that would break every existing caller.

Override or overload? The parameter list decides

Override ✅

same signature

Main.java
1class Dog extends Animal {
2 @Override
3 void sound() {
4 System.out.println("Woof");
5 }
6}
  • Replaces the inherited behaviour
  • Chosen at runtime by the object's real type
  • animal.sound() prints Woof

Accidental overload ❌

different parameters

Main.java
1class Dog extends Animal {
2 void sound(String volume) {
3 System.out.println("Woof " + volume);
4 }
5}
  • A brand-new method; the parent's sound() is still inherited
  • dog.sound() still prints the generic message
  • @Override on it would be a compile error — which is why you add it
Covariant return types are allowed
Main.java
1class AnimalShelter {
2 Animal adopt() { return new Animal("Creature"); }
3}
4
5class DogShelter extends AnimalShelter {
6 @Override
7 Dog adopt() { return new Dog("Rex"); } // Dog IS-A Animal → legal
8}
Returning something *more specific* never breaks a caller who expected an Animal — so Java permits it. Returning something more general would break them, so it is forbidden.

`final` and `static` are the two escape hatches

final void pay() forbids overriding — useful when a method enforces something that must never change. A static method belongs to the class, not the object, so redeclaring it in a child *hides* it (resolved by the reference type at compile time) rather than overriding it. Interview trap: static methods are never polymorphic.

Common mistakes

Wrong@Override void sound(String volume) { } // parent declares sound()
WhyDifferent parameter list → not an override; with the annotation it is a compile error, without it a silent bug.
FixMatch the parent's parameter list exactly, or intentionally overload with a different name.
WrongOverriding a `public` method as `protected`.
WhyYou cannot narrow access — existing callers would break.
FixKeep the same access level, or widen it.
WrongWriting `Sound()` or `sound2()` because 'the name was taken'.
WhyReusing the *same* name is the entire point — the caller must not have to know the subtype.
FixKeep the name, change the body.

Lesson playground

Free practice

The parent's describe() calls draw(). Override draw() in Square and watch describe() change behaviour without being touched. Now add a Triangle.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

Engineer overrides one method and inherits the other. What is printed?

Main.java
1class Employee {
2 void work() {
3 System.out.println("Working");
4 }
5
6 void badge() {
7 System.out.println("Employee badge");
8 }
9}
10
11class Engineer extends Employee {
12 @Override
13 void work() {
14 System.out.println("Writing code");
15 }
16}
17
18public class Main {
19 public static void main(String[] args) {
20 Engineer e = new Engineer();
21 e.work();
22 e.badge();
23 }
24}

Summary

  • Overriding = same name, same parameter list, compatible return type, access not narrowed.
  • `@Override` turns a silent typo into an instant compile error — always write it.
  • Different parameters make an overload, not an override.
  • `static`, `final` and `private` methods cannot be overridden.