Java inheritance and method overriding
Use a superclass reference to call subclass behavior.
On this page
Classes and instance methods.
- Use a superclass reference to call subclass behavior.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
extends establishes a superclass relationship. An overriding instance method replaces inherited behavior for that object's runtime type.
The @Override annotation asks the compiler to check that a method really overrides an inherited declaration. The reference type controls available operations; the runtime object controls virtual instance-method dispatch.
Code example
class Animal {
String speak() { return "sound"; }
}
class Dog extends Animal {
@Override String speak() { return "woof"; }
}
class Cat extends Animal {
@Override String speak() { return "meow"; }
}
class Main {
public static void main(String[] args) {
Animal[] animals = {new Dog(), new Cat()};
for (Animal animal : animals) {
System.out.println(animal.speak());
}
}
}woof meow
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
class Animal { String speak() { return "sound"; }}class Dog extends Animal { @Override String speak() { return "woof"; }}class Cat extends Animal { @Override String speak() { return "meow"; }}class Main { public static void main(String[] args) { Animal[] animals = {new Dog(), new Cat()}; for (Animal animal : animals) { System.out.println(animal.speak()); } }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Store two subclass references in a superclass-typed array. | animals = [Dog, Cat] | — | |
| The first call dispatches to Dog. | return = woof | — | |
| Print the first sound. | return = woof | woof | |
| The next iteration dispatches to Cat. | return = meow | woof | |
| Print the second sound. | return = meow | woof meow |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(n) calls for n objects, O(n) array storage.
- Overloading chooses among parameter signatures; overriding supplies subclass behavior for the same signature.
- Static methods do not use this instance dispatch behavior.
Try it yourself
Add Bird extends Animal with speak returning chirp.
Reveal answer and reasoning
Adding new Bird() to the array makes the loop print chirp as another line.