Menu
Coddy logo textTech

Total Area

Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 60 of 70.

challenge icon

Challenge

Easy

Let's add a powerful feature to your ShapeCollection—the ability to calculate the total area of all shapes it contains. This is where polymorphism really shines: your collection can call :getArea() on any shape without knowing whether it's a rectangle or circle.

You'll continue building on your existing project files:

  • Shape.lua: Your base Shape class (unchanged).
  • Rectangle.lua: Your Rectangle class with :getArea() and :getPerimeter().
  • Circle.lua: Your Circle class with :getArea() and :getPerimeter().
  • ShapeCollection.lua: Extend your collection class by adding a :getTotalArea() method. This method should iterate through all stored shapes, call :getArea() on each one, and return the sum of all areas.
  • main.lua: Require your modules, read dimensions from input, create a Rectangle and a Circle, add both to a ShapeCollection, then print the total area of all shapes in the collection.

The beauty of this approach is that :getTotalArea() doesn't need separate logic for rectangles and circles—it simply trusts that every shape in the collection has a :getArea() method. You could add triangles, hexagons, or any other shape later, and the total area calculation would work without modification.

Input: Three lines—width (number), height (number), and radius (number).

Output: A single line containing the total area of all shapes in the collection.

Try it yourself

-- Require the Rectangle module
local Rectangle = require('Rectangle')

-- Require the Circle module
local Circle = require('Circle')

-- Require the ShapeCollection module
local ShapeCollection = require('ShapeCollection')

-- Read width and height from input
local width = tonumber(io.read())
local height = tonumber(io.read())
local radius = tonumber(io.read())

-- Create a new Rectangle instance with the given dimensions
local rect = Rectangle:new(width, height)

-- Create a new Circle instance with the given radius
local circ = Circle:new(radius)

-- Create a new ShapeCollection
local collection = ShapeCollection:new()

-- Add both shapes to the collection
collection:addShape(rect)
collection:addShape(circ)

-- Print the total area of all shapes in the collection
print(collection:getTotalArea())

All lessons in Object Oriented Programming