I’m currently in the process of learning OOP and I have a very basic example setup and I’m a bit confused about methods in an inherited class. I have an enemy class and then I have a boss class that inherits from enemy (because they’re both enemies, but the boss might have a few differences) is it possible to give the inherited class the same method which does its own thing? So the enemy attack method is the default which gets used if the inherited class doesn’t have its own. Also in the inherited class I added a random IsDeadly variable to it, but I can’t figure out how to access it lol.
local Enemy = {}
Enemy.__index = Enemy
function Enemy.new(Name,HP,MP,Lvl,Model)
return setmetatable({
Name = Name,
HP = HP,
MP = MP,
Lvl = Lvl,
Model = Model
}, Enemy)
end
--this would be the default
function Enemy:Attack()
warn("basic attacks")
end
return Enemy
local Enemy = require(game.ServerScriptService.OOPTesting.Enemy)
--Inheritance
local Boss = setmetatable({}, Enemy)
Boss.__index = Boss
function Boss.new(Name,HP,MP,Lvl,Model,IsDeadly)
local newBoss = Enemy.new(Name, HP, MP, Lvl, Model)
setmetatable(newBoss, Boss)
newBoss.IsDeadly = IsDeadly
return newBoss
end
--use this instead of default
function Boss:Attack()
warn("attack unique to this boss")
end
function Boss:IsDeadly()
warn(self.IsDeadly)
end
return Enemy
It won’t overwrite it per se, it will just be the method used for the inherited class. Method calls on the base class will still use the base method. In addition, if you want to use the base method inside of the overwriting method, you can use something like this
function Inheritor:Method(...)
-- do stuff
baseClass.Method(self, ...)
end
It’s also a good idea to include a link to the base class in your inheritors.
Oh, this might be an issue too. I would alter this to be
local Boss = setmetatable({}, {__index = Enemy})
You shouldn’t notice a difference in your current code, but it will come back to bite you if you ever try to inherit Boss.
Typically when I set up classes (and bear in mind that it’s been a while) I usually start them something like this
Ok so this is a bit random, but after experimenting more I feel like this oop stuff is just useless I’m most likely just doing things wrong, but idk it seems like you can’t even give an inherited class it’s own method without having to make it shared?
I tried adding this to the inherited class
function Boss:Test()
warn("test")
end
but I just get an error “ServerScriptService.OOPTesting.Script:7: attempt to call a nil value” so I tried doing this
function Enemy:Test()
warn("test")
end
and now it works however now the enemy class can use that method which I don’t want lol.
Some will argue OOP is useless, some will argue it’s the greatest thing ever, but almost everyone agrees inheritance is evil and will come back to haunt you when you have a massive hierarchy that’s not easy to change.