Card 02/ 09
Polymorphism Example: One Loop Drawing Three Shapes
A loop that draws a circle, a square and a line without knowing which is which.
Polymorphism means one call runs different code depending on the object: a loop over a list of a parent type calls each object's own override, its replacement for the parent's method, with no if and no type names. Three classes that each draw themselves, and a loop that draws all of them:
abstract class Shape { abstract void draw(); }
class Circle extends Shape { void draw() { System.out.println("circle"); } }
class Square extends Shape { void draw() { System.out.println("square"); } }
class Line extends Shape { void draw() { System.out.println("line"); } }List<Shape> shapes = List.of(new Circle(), new Square(), new Line());
for (Shape s : shapes) {
s.draw();
}circle
square
lineThe loop variable is declared Shape and the objects are three different classes. Line 4 runs a different body on every pass, and the loop contains no if, no type name and no test.
The list is typed List<Shape>, which is what makes the loop legal, and the objects inside it keep their real classes. The declared type decided what could be called; the actual object decided what ran.
← → move through sections and cards