Menu
Coddy logo textTech

Circle Class

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

challenge icon

Challenge

Easy

Let's continue building our Shape Manager by adding a Circle class alongside the Rectangle you created in the previous lesson.

You'll work with four files to keep your shapes organized:

  • Shape.lua: Your base Shape class with :new(name) and :getName().
  • Rectangle.lua: Your Rectangle class from the previous challenge with :getArea().
  • Circle.lua: Create a Circle class that inherits from Shape. The constructor should accept a radius, call the parent constructor with the name "Circle", and store the radius. Add a :getArea() method that calculates the circle's area using the formula πr². Use math.pi for the value of π.
  • main.lua: Require both your Rectangle and Circle modules. Read three values from input: a rectangle's width, a rectangle's height, and a circle's radius. Create one instance of each shape and print four lines—the rectangle's name, the rectangle's area, the circle's name, and the circle's area.

Both shapes now share the same interface through inheritance—each has a :getName() method from Shape and its own :getArea() implementation. This common interface will become useful in upcoming lessons.

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

Output: Four lines—rectangle's name, rectangle's area, circle's name, circle's area.

Try it yourself

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

-- Require the Circle module
-- TODO: Require the Circle module here

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

-- TODO: Read the radius from input

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

-- TODO: Create a new Circle instance with the given radius

-- Print the rectangle's name and area
print(rect:getName())
print(rect:getArea())

-- TODO: Print the circle's name and area

All lessons in Object Oriented Programming