Skip to content
Codewilds

Lesson 25 of 34 · Inheritance & Interfaces

Java Method Overriding and Polymorphism

medium20 XP3 min read

In the last lesson a Car inherited describe() from Vehicle unchanged. Often, though, a subclass needs to do the same job differently: every shape has an area, but a circle computes it differently from a rectangle.

That is what method overriding is for — and combined with superclass references it gives you polymorphism, one of the most powerful ideas in object-oriented programming.

Overriding a method

A subclass overrides an inherited method by declaring a method with the same name, the same parameter types and a compatible return type:

class Animal {
    String sound() {
        return "...";
    }

    String speak() {
        return "It says " + sound();
    }
}

class Dog extends Animal {
    @Override
    String sound() {
        return "Woof";
    }
}

class Cat extends Animal {
    @Override
    String sound() {
        return "Meow";
    }
}

@Override is optional but you should always write it: it asks the compiler to check that you really override something. Misspell the name (sounds()) and you get method does not override or implement a method from a supertype instead of a silent bug.

Polymorphism: one type, many forms

A variable of a superclass type can hold any subclass object. When you call a method, Java looks at the actual object at run time and runs its version — this is called dynamic dispatch:

Animal[] pets = { new Dog(), new Cat(), new Animal() };
for (Animal pet : pets) {
    System.out.println(pet.speak());
}
It says Woof
It says Meow
It says ...

speak() is written once, in Animal, yet it calls the right sound() for each pet. You can add a Cow tomorrow and this loop works unchanged. Lists work the same way: a List<Animal> can hold dogs and cats side by side.

The declared type decides which methods you may call; the object decides which code runs. With Animal pet = new Dog();, calling pet.fetch() does not compile — Animal has no fetch().

super.method() and instanceof

An override can reuse the parent's version with super:

class Puppy extends Dog {
    @Override
    String sound() {
        return super.sound() + "! " + super.sound() + "!";  // "Woof! Woof!"
    }
}

When you really need a subclass-only method, check the type first. A pattern gives you a correctly typed variable in one step:

if (pet instanceof Dog dog) {
    System.out.println(dog.sound() + " - good dog");
}

final, and overloading vs overriding

A final method cannot be overridden, and a final class cannot be extended at all — String is final, so nobody can change how Strings behave.

Don't confuse the two "O" words: overloading means same name, different parameters, chosen by the compiler; overriding means same signature in a subclass, chosen at run time by the object.

Common mistakes

  • Accidental overloading: double area(int precision) in a subclass does not override area(); @Override would catch it.
  • Weaker access: an override cannot be less visible — overriding a public method without public fails with attempting to assign weaker access privileges.
  • Expecting fields to be polymorphic: only methods are dispatched dynamically. Use methods, not public fields, for behaviour that varies.
  • Overusing instanceof: if you write long instanceof chains, the behaviour probably belongs in an overridden method instead.

Assignment

Shape provides name(), area() and describe() (which uses both). Override methods so every shape reports the right values:

  1. Circle(double radius) — name() returns "circle", area() returns π·r² (use Math.PI).
  2. Rectangle(double width, double height) — name() returns "rectangle", area() returns width × height.
  3. Square(double side) extends Rectangle — name() returns "square"; its area must come from Rectangle.
  4. Main.totalArea(List<Shape> shapes) — the sum of all areas (0.0 for an empty list).
  5. Main.largest(List<Shape> shapes) — the shape with the biggest area (the first one on a tie), or null for an empty list.
Shape s = new Circle(2);
s.describe()              // "circle with area 12.57"
new Square(3).describe()  // "square with area 9.00"

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Polymorphism in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 25 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.