Facebook Pixel

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.

CommandBehaviorOutput
["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.

Example
Input
7
square 4
rectangle 3 5
triangle 6 4
count
square 2
total
count
Output
Shapes: 3
Total area: 47
Shapes: 4
Explanation
The first three commands add a square (area 16), a rectangle (area 15), and a triangle (area 12) without producing output. The `count` after three shapes returns "Shapes: 3". Adding a second square (area 4) brings the canvas to four shapes. The `total` sums 16+15+12+4=47. The final `count` reports 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.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro