Single inheritance

When using single inheritance, any class can inherit functionality from only one super class. To implement single inheritance, create a new class through an existing constructor. This can be a bit confusing, so let's see an example.

Start by creating an Animal class; this will be the base class:

Animal = {
sound = ""
}

Animal.new = function(self, object)
object = object or {}
setmetatable(object, self)
self.__index = self
return object
end

Animal.MakeSound = function(self)
print(self.sound)
end

Not every animal is going to make the same sound. Create two new classes, dog and cat, that extend Animal:

-- Dog is a class, not an object (instance)
Dog = Animal:new()
Dog.sound = "woof"
-- Cat is a class, not an Object (instance)
Cat = Animal:new()
Cat.sound = "meow"
Cat.angry = false
Cat.MakeSound = function(self)
if self.angry then
print("hissss)
else
print(self.sound)
end
end

In this code, Dog is a new class, not an instance of the Animal class. This can be a bit tricky at first, as the syntax is similar. Dog simply overrides the sound variable. Cat also extends Animal. But Cat provides its own implementation of MakeSound, which lets the cat make different sounds.

Regardless of whether an animal is a Cat or a Dog, we can treat them both as an Animal. We know that every object that is a Cat or a Dog is also an Animal. And we know that every Animal has a MakeSound function. The following code generates some animals and has them all make sounds:

animals = { Cat:new(), Dog:new(), Cat:new() }
animals[1].angry = true

for i,v in ipairs(animals) do
-- The current animal is stored in the v variable.
-- It doesn't matter if the animal is a Dog or a Cat
-- Both Dog and Cat extend Animal, which is guaranteed to contain a MakeSound function.
v:MakeSound()
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.31.163