Menu
Coddy logo textTech

Rectangle Class

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

challenge icon

Challenge

Easy

Now let's expand our Shape Manager by creating a Rectangle class that inherits from the base Shape you built in the previous lesson.

You'll work with three files to keep your code organized:

  • Shape.lua: Your base Shape class from the previous challenge (with :new(name) and :getName()).
  • Rectangle.lua: Create a Rectangle class that inherits from Shape. The constructor should accept width and height, call the parent constructor with the name "Rectangle", and store the dimensions. Add a :getArea() method that calculates and returns the rectangle's area.
  • main.lua: Require your Rectangle module, read width and height from input, create a Rectangle instance, and print its name followed by its area on separate lines.

Remember to set up the inheritance link properly so Rectangle instances can access Shape's methods through the prototype chain.

Input: Two lines—the first containing the width (number), the second containing the height (number).

Output: Two lines—the rectangle's name from :getName(), then its area from :getArea().

Try it yourself

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

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

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

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

All lessons in Object Oriented Programming