--父类
local ParentClass = {
id = "085",
name = "紫霞",
--ParentClass.__index = ParentClass #自索引错误写法, __index赋值的是一个nil值, 也就是说ParentClass是一个nil值
}
--[[
function ParentClass.showInfo() --#报错, "."不支持self, 必须是":"调用才支持self
printEx("编号:" .. self.id .. " 名字:" .. self.name)
end
--]]
function ParentClass:showInfo() --为什么会在外面单独赋值, 而不是写在ParentClass表里面赋值, 因为没有这种写法, 必须写在外面赋值
printEx("编号:" .. self.id .. " 名字:" .. self.name)
end
ParentClass.__index = ParentClass --自索引
--写在自索引赋值后面子类继承后依旧可以调用此函数
function ParentClass:method()
printEx("我是父类的方法")
end
--ParentClass.showInfo() #报错, .不支持self, 必须是:调用才支持
ParentClass:showInfo()
--子类
local SonClass = {
id = "1085",
name = "紫霞的儿子"
}
function SonClass:showInfo() --显示信息方法重写
printEx("编号:" .. self.id .. " 名字:" .. self.name)
end
SonClass:showInfo()
--子类继承父类需要用到元表中的__index 或者 传参(不推荐)
setmetatable(SonClass, ParentClass) --子类继承父类中的字段
--调用子类重写的showInfo方法
SonClass:showInfo()
--调用继承父类的method方法
SonClass:method()
--实例化
local comClass = {id = "000", name = "无", age = 0}
function comClass:showInfo()
printEx("id: " .. self.id .. ", 名字: " .. self.name .. ", 年龄: " .. self.age)
end
function comClass:new(obj)
--下面这行代码的含义: 避免多重继承时, 导致self(谁调用就是谁)没有__index无法串连起来
self.__index = rawget(self, __index) or self
--返回具有元表的表(继承)
return setmetatable(obj or {}, self)
end
comClass.__index = comClass
--实例化1(继承通用类)
local instantiation1 = comClass:new({id = "001", name = "熏悟空", age = 85838})
print(instantiation1:showInfo())
--实例化2(继承通用类)
local instantiation2 = comClass:new({id = "002", name = "花蝴蝶", age = 547})
print(instantiation2:showInfo())
--实例化3(继承实例化1类, 间接继承通用类)
local instantiation3 = instantiation1:new({id = "003", name = "猿猴", age = 192})
print(instantiation3:showInfo())