Card 02/ 09

ExampleDifficulty: Intermediate1 min

One Loop Over Three Shapes

Three classes that each draw themselves, and a loop that draws all of them without knowing what any of them is.

java
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"); } }
java
List<Shape> shapes = List.of(new Circle(), new Square(), new Line());

for (Shape s : shapes) {
    s.draw();
}
text
circle
square
line

The 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.