Overriding and Polymorphism
Override parent methods and achieve runtime polymorphic dispatch.
Method Overriding
A child class overrides a parent method by defining a method with the same name. When called on a child instance, the child's version runs. The parent's version is still accessible via Parent.method(self).
local Shape={} Shape.__index=Shape
function Shape:area() return 0 end
function Shape:describe() print(type(self).." area="..self:area()) end
local Circle={} Circle.__index=Circle
setmetatable(Circle,{__index=Shape})
function Circle.new(r) return setmetatable({r=r},Circle) end
function Circle:area() return math.pi*self.r^2 end
local Square={} Square.__index=Square
setmetatable(Square,{__index=Shape})
function Square.new(s) return setmetatable({s=s},Square) end
function Square:area() return self.s^2 end
Circle.new(5):describe()
Square.new(4):describe()Polymorphic Dispatch
Polymorphism: different object types respond to the same message differently. A function that accepts any "shape" and calls :area() works for any shape type — each responds with its own implementation.
local shapes={
Circle.new(3),
Square.new(4),
Circle.new(1),
}
local total=0
for _,shape in ipairs(shapes) do
total=total+shape:area()
end
print(string.format("Total area: %.2f",total))All lessons in this course
- Single Inheritance with __index Chaining
- Calling Parent Methods with super
- Mixin Patterns
- Overriding and Polymorphism