Rectangle Class
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 56 of 70.
Challenge
EasyNow 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 acceptwidthandheight, 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
1The 'Self' Concept
Tables with FunctionsExplicit 'self'The Colon SyntaxDot vs ColonRecap - Moving Point4Project: Digital Bank
Project SetupDeposit Method7Polymorphism & Overriding
Overriding MethodsCalling Parent MethodsDuck TypingCommon InterfaceChecking TypeRecap - Employee Roles10Project: Shape Manager
Project SetupRectangle Class2Class Prototype Pattern
The Prototype ConceptLinking with __indexThe :new() ConstructorInitializing AttributesIndependent InstancesRecap - Car Factory5Operator Overloading in OOP
Adding ObjectsSubtracting ObjectsConcatenating ObjectsComparing Objects (<, >)Recap - Wallet Math8Encapsulation
Naming ConventionsClosures for PrivacyAccess via ClosuresRead-Only TablesValidation LogicRecap - Secure Vault11Design Patterns (Lite)
Factory FunctionsSingleton TableIterator PatternObserver (Listener)Recap - Logger Factory3Object State and Behavior
Instance VariablesGetter MethodsSetter MethodsCalculated PropertiesFormatting StringsEquality ChecksRecap - Student Grade6Inheritance Basics
The Inheritance SetupInheriting MethodsExtending the ConstructorAdding Child MethodsShared vs UniqueRecap - Shape Hierarchy