AI Hints
Home›Java Tutorial›Overriding, Polymorphism and Abstract Classes
Java · Lesson 77 of 120

Polymorphism

Many forms, one call.

⏱ 2 min read▶ Video at 1:37:02🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Polymorphism means many forms. A variable of type Animal can hold a dog, a cat, or a cow. And calling speak does the right thing for each one.

  • Many forms
  • Animal holds any animal
  • The right method runs

One loop, many animals

This array has the type Animal. But it holds dogs, cats, and a cow. The loop treats them all just as animals. Yet each one speaks with its own sound. Java picks the method at runtime, based on the real object. Run it. Woof, meow, moo, and woof.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Animal[] farm = {
            new Dog("Rex"),
            new Cat("Tom"),
            new Cow("Daisy"),
            new Dog("Fido")
        };
        for (Animal a : farm) {
            a.speak();
        }
    }
}
Output
Rex says Woof
Tom says Meow
Daisy says Moo
Fido says Woof
Also uses Animal.java
public class Animal {
    protected String name;
    public Animal(String name) { this.name = name; }

    public String sound() { return "..."; }

    public void speak() {
        System.out.println(name + " says " + sound());
    }
}
Also uses Dog.java
public class Dog extends Animal {
    public Dog(String name) { super(name); }

    @Override
    public String sound() { return "Woof"; }
}
Also uses Cat.java
public class Cat extends Animal {
    public Cat(String name) { super(name); }

    @Override
    public String sound() { return "Meow"; }
}
Also uses Cow.java
public class Cow extends Animal {
    public Cow(String name) { super(name); }

    @Override
    public String sound() { return "Moo"; }
}

Why it matters

Code can work with the general type, Animal, and never needs to know the exact kind. To add a new animal, you write one new class. The loop doesn't change at all. This keeps big programs flexible.

keyvalue
Write code forthe general type
Java picksthe real object's method
Add a classnothing else changes
Resultflexible code

Summary

Polymorphism lets one variable hold many kinds of objects, and calls the right method for each. Next, classes that are only meant to be extended.

Key takeaways
  • Animal a = new Dog()
  • Real object decides
  • Add types freely
Next up: Abstract Classes — incomplete on purpose