Summary - Polymorphism
- Java course
- Intermediate
- Lesson 64/116
- 5 min
Combine dynamic binding and pattern matching to write a shape renderer.
Summary - Polymorphism
In this group you learned polymorphism: a superclass reference holds a subclass instance; method calls dispatch dynamically. With override you replace a parent method; the @Override annotation checks this at compile time.
Abstract classes and interfaces provide contracts; instanceof and pattern matching let you test types. This summary brings them together in a small task.
Practice A polymorphic bird list
Define abstract class Bird with an abstract String sound(); method. Define class Sparrow extends Bird that overrides sound with @Override returning "Chirp". Define class Crow extends Bird that overrides sound with @Override returning "Caw". In main, create a List<Bird> birds = new ArrayList<>();, add new Sparrow() and new Crow(), and print each sound on its own line with a for-each loop.
Starter code
import java.util.List;
import java.util.ArrayList;
// abstract Bird: abstract String sound();
// Sparrow extends Bird; @Override sound = "Chirp"
// Crow extends Bird; @Override sound = "Caw"
// main: build the birds list, add two birds, print via for-eachSample solution
abstract class Bird {
abstract String sound();
}
class Sparrow extends Bird {
@Override
String sound() { return "Chirp"; }
}
class Crow extends Bird {
@Override
String sound() { return "Caw"; }
}
public class Main {
public static void main(String[] args) {
List<Bird> birds = new ArrayList<>();
birds.add(new Sparrow());
birds.add(new Crow());
for (Bird b : birds) {
System.out.println(b.sound());
}
}
}Expected output
Chirp Caw
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the core polymorphism syntax?
- new Circle() = Shape s
- Shape s = new Circle(); Correct answer
- Circle extends Shape implements
- instanceof Circle s
Explanation: A supertype variable receives a subtype instance.
2 Complete the override annotation
class Sparrow extends Bird {
____
String sound() { return "Chirp"; }
}
class Sparrow extends Bird {
@Override
String sound() { return "Chirp"; }
}
Explanation: @Override enables compiler checking.
3 Match the polymorphism summary
| Term | Meaning |
|---|---|
virtual |
Default method behavior |
abstract |
Non-instantiable reference type |
interface |
Multiple inheritance contract |
instanceof |
Type check and pattern matching |