Exercise: Polymorphism
This exercise puts the polymorphism lesson into code.
Scenario
A canvas accumulates shapes and answers queries about them. Three shape types are supported:
squares, rectangles, and triangles. Each shape knows how to compute its own area. The canvas
stores shapes as a flat list and sums their areas by calling area() on each one — no type
checks, no isinstance calls, no switch statements. Each command produces exactly one output
line.
Commands
The program reads one command per line and prints one line of output per command.
| Command | Behavior | Output |
|---|---|---|
["square", s] | Add a square with side s; area is s * s | (no output) |
["rectangle", w, h] | Add a rectangle; area is w * h | (no output) |
["triangle", b, h] | Add a right triangle; area is (b * h) / 2 | (no output) |
["count"] | Report the number of shapes added so far | "Shapes: <n>" |
["total"] | Report the sum of all shape areas | "Total area: <sum>" |
All dimensions are integers. Test inputs guarantee that b * h is always even, so triangle
areas are always integers.
7 square 4 rectangle 3 5 triangle 6 4 count square 2 total count
Shapes: 3 Total area: 47 Shapes: 4
Your task
Create the Square, Rectangle, and Triangle classes — each subclasses Shape and implements area() — then run the tests. The dispatcher below already calls Square(s), Rectangle(w, h), and Triangle(b, h) by name, so the code tells you exactly what to build.