Adding Child Methods
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 34 of 70.
Inheritance lets child classes access parent methods, but the real power comes from adding new methods that only the child has. A Dog can do everything an Animal can, plus things unique to dogs—like barking.
Adding a child-specific method is straightforward: just define it on the child class table. Since instances look up methods in their own class first, they'll find the new method without affecting the parent.
local Animal = {}
Animal.__index = Animal
function Animal:new(name)
local obj = {name = name}
setmetatable(obj, Animal)
return obj
end
function Animal:breathe()
print(self.name .. " is breathing")
end
-- Dog inherits from Animal
local Dog = {}
Dog.__index = Dog
setmetatable(Dog, {__index = Animal})
function Dog:new(name)
local obj = Animal.new(Animal, name)
setmetatable(obj, Dog)
return obj
end
-- New method only in Dog
function Dog:bark()
print(self.name .. " says: Woof!")
endNow Dog instances can use both inherited and unique methods:
local buddy = Dog:new("Buddy")
buddy:breathe() -- Output: Buddy is breathing (inherited)
buddy:bark() -- Output: Buddy says: Woof! (child-only)The parent class remains unchanged—calling :bark() on a plain Animal would fail since that method doesn't exist there. This is how inheritance lets you specialize behavior while keeping shared functionality in one place.
Challenge
EasyLet's build a pet hierarchy where cats have their own special ability! You'll create a Pet parent class and a Cat child class, where Cat inherits everything from Pet but also has a unique method that only cats can do.
You'll organize your code across three files:
Pet.lua: Define your parent class with a:new(name)constructor that stores the pet's name. Include a:greet()method that prints the pet's name followed bysays hello. Set up the standard class pattern and return the class.Cat.lua: Define your child class that inherits from Pet. Your Cat's:new(name)constructor should call the parent constructor to initialize the name, then re-link the metatable to Cat. Add a child-specific:purr()method that prints the cat's name followed bypurrs contentedly. This method exists only in Cat—Pet doesn't have it!main.lua: Require your Cat module, read a name from input, create a Cat instance, and demonstrate that it can use both the inherited:greet()method and its own unique:purr()method.
You will receive one input: the cat's name.
In your main file, create a Cat with the given name, then call :greet() followed by :purr() on separate lines.
For example, if the input is Whiskers, the output should be:
Whiskers says hello
Whiskers purrs contentedlyThe first line comes from the inherited :greet() method defined in Pet, while the second line comes from the :purr() method that only exists in Cat. This demonstrates how child classes can do everything their parent can, plus their own specialized behaviors!
Try it yourself
-- main.lua: Create a Cat and demonstrate inheritance
local Cat = require('Cat')
-- Read the cat's name from input
local name = io.read()
-- TODO: Create a Cat instance with the given name
-- TODO: Call the inherited :greet() method (from Pet)
-- TODO: Call the Cat-specific :purr() method
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ClassCircle ClassPerimeter MethodShape CollectionTotal AreaFilter Shapes2Class 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