实现继承的原理:利用table中的元表来实现 __index
__index元方法:用于查看表中元素或方法是否存在 如果不存在则返回nil 如果存在 则返回__idnex表中的结果
--单一继承的实现 利用元表来实现继承
Account = {name = "lili", balance = 10}
function Account:widthdraw(value)
self.balance = self.balance + value
end
function Account:new(o)
o = o or {}
setmetatable(o, self)
self. __index = self
return o
end
local rto = Account:new()
rto:widthdraw(1000)
print("father area")
print("balance = " .. rto.balance)
print("name = " .. rto.name)
--子类继承父类
childAccount = Account:new({height = 200})
--子类重写父类方法
function childAccount:widthdraw(value)
print("I am child ")
self.balance = self.balance - value
end
local cto = childAccount:new()
cto:widthdraw(1)
print("-----------------")
print("child area")
print("balance = " .. cto.balance)
print("name = " .. cto.name)
print("height = " .. cto.height)
childAccount = Account:new({height = 200}) 产生子类 在Account:new()中将__index设为你自己 是一个table 当cto访问balance时 由于自己不存在此字段 会去元表Account{}中查找 存在返回结果 不存在会提示在访问一个不存在的nil值
第二种实现继承
Father.lua
--类的声明 声明了类名和属性 属性初始值
Father = {x = 20, y = 40}
--设置元表的索引
--当访问Father中不存在字段信息时 需要在元表中通过__index元方法查找
--这里设置__index为自身
Father. __index = Father
--构造方法
function Father:new(x, y)
local self = {}
setmetatable(self, Father) --将self的元表设为Father
self.x = x
self.y = y
return self
end
function Father:Test()
print("x = " .. self.x)
print("y = " .. self.y)
end
function Father:add()
self.x = self.x + 10000
self.y = self.y + 2000
end
return Father
child.lua
require "Father"
--声明了child的新属性
child = {z = 1000, name = "hqk"}
--将child的元表设置为Father
setmetatable(child, Father)
child. __index = child
function child:new(x, y, z, name)
local self = {}
--调用父类的构造函数构造父类部分
self = Father:new(x, y)
--将对象自身的元表设为child类
setmetatable(self, child)
self.z = z
self.name = name
return self
end
function child:Test()
print("x = " .. self.x)
print("y = " .. self.y)
print("z = " .. self.z)
print("name = " .. self.name)
end
function child:Sub()
self.x = self.x - 100
self.y = self.y - 1000
self.z = self.z * 2
end
return child
jtest.lua 测试
require "Father"
require "child"
print("Father area")
print("construct Father object")
local f = Father:new()
print("use self function")
Father:add()
f:Test()
print("-----------------")
print("Child area")
print("construct child object")
f = child:new() --实例化子对象
print("use Father's function")
f:add() --子类调用父类成员方法
print("use self function")
f:Sub()
print("use rewrite function")
f:Test() --子类调用重写的方法
————————————————
版权声明:本文为优快云博主「hanqingkuo」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/sinat_28603977/article/details/89029687