Object-Oriented JavaExtra· 35 min read

Polymorphism (Overriding)

A child class can replace a parent method, so the same call behaves differently per object.

What you will learn

  • Override a parent method
  • See the same call act differently
  • Use the @Override label safely

Same call, different behaviour

Polymorphism is a big word for a simple idea: the same method call can do different things depending on the object. A child class can override (replace) a method it inherited.

Imagine an Animal with a speak() method. A Dog and a Cat each override it to make their own sound.

Dog and Cat each override speak()
public class Animal {
    void speak() {
        System.out.println("Some animal sound");
    }
}

public class Dog extends Animal {
    @Override
    void speak() {
        System.out.println("Woof!");
    }
}

public class Cat extends Animal {
    @Override
    void speak() {
        System.out.println("Meow!");
    }
}

Note: Output: (No output yet — these are the classes. Each child has its own version of speak(), replacing the parent one. We see the magic when we call them next.)

The same line, three results

One loop, calling speak() on different objects
public class Main {
    public static void main(String[] args) {
        Animal[] animals = { new Animal(), new Dog(), new Cat() };

        for (Animal a : animals) {
            a.speak();   // same call — different result each time
        }
    }
}

Note: Output: Some animal sound Woof! Meow! The SAME line a.speak() printed three different things. Java looks at the REAL object (Animal, Dog or Cat) and runs that object version of speak(). That is polymorphism in action.

What @Override means

@Override is a label that tells Java you intend to replace a parent method. It is optional but smart: if you spell the method name wrong, Java gives an error instead of silently making a brand-new method.

Watch out: Without @Override, a small typo like speakk() would compile as a different method, and the parent speak() would run instead — a confusing bug. The @Override label catches this for you.

Tip: Polymorphism lets you treat many types the same way. You can store a Dog and a Cat in an Animal[] array and loop over them with one piece of code, even though each behaves differently.

Q. What does overriding a method let you do?

Answer: Overriding replaces an inherited method in the child class. The same call (like a.speak()) then runs the version that matches the real object.

✍️ Practice

  1. Create a Shape class with an area() method, and override it in Circle and Rectangle.
  2. Loop over a Shape[] array and print each area to see different results.

🏠 Homework

  1. Make an Employee parent with a pay() method, then Manager and Intern subclasses that override it differently. Loop over an array of them.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →