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.
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
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?
✍️ Practice
- Create a
Shapeclass with anarea()method, and override it inCircleandRectangle. - Loop over a
Shape[]array and print each area to see different results.
🏠 Homework
- Make an
Employeeparent with apay()method, thenManagerandInternsubclasses that override it differently. Loop over an array of them.