I’m learning OOP and created a base-class (AnimalClass) and have sub-classes inheriting from the base class (Dog, Cat, Penguin)
I see two different ways to do it, and am not sure which one is the better way. If anyone could give me some clarification, I would appreciate it a lot
Sub-Class ModuleScript (Dog)
Version 1
local AnimalClass = require(script.Parent)
local DogClass = {}
DogClass.__index = DogClass
setmetatable(DogClass, AnimalClass)
function DogClass.new(name, age)
local dog = setmetatable({}, DogClass)
dog.Name = name
dog.Age = age
return dog
end
function DogClass:Bark()
print(self.Name, "is barking!")
end
return DogClass
Version 2
local AnimalClass = require(script.Parent)
local DogClass = setmetatable({}, AnimalClass)
DogClass.__index = DogClass
function DogClass.new(name, age)
local dog = setmetatable(AnimalClass.new(name, age), DogClass)
return dog
end
function DogClass:Bark()
print(self.Name, "is barking!")
end
return DogClass
Base Class (Animal)
local AnimalClass = {}
AnimalClass.__index = AnimalClass
function AnimalClass.new(name: string, age: number)
local animal = setmetatable({}, AnimalClass)
animal.Name = name
animal.Age = age
return animal
end
function AnimalClass:Eat(food: string)
print(self.Name, "is eating", food)
end
function AnimalClass:IncreaseAge()
self.Age += 1
print(self.Name, "is", self.Age, "years old")
end
return AnimalClass
Second would be better as in that case you would be inheriting the properties from AnimalClass. You wouldn’t want to have to rewrite the properties if you don’t have to.
You would keep both constructors, then call the inherited class’s constructor in the subclass constructor, it’s this version you’d keep:
Note that in this version, you aren’t explicitly rewriting the properties that will be present in all the AnimalClass objects (you aren’t writing dog.Name, dog.Age…); it’s the inherited class (AnimalClass) that does this work
The only properties you’d explicitly write in the dogClass constructor are the properties that are specific to the dogClass (say if you had a property like “BarksLoudly” or something like that, that would only be present in your dog class, then you could reference this property inside of your dogClass methods [dogClass:Bark()])
Just want to point something out in the first version, I think you’re not properly setting the __index metamethod of the DogClass, so in the first example, some bugs may occur.