Lua 面向对象 继承

Lua 面向对象 继承

继承是面向对象的方法的一个主要特征,是使用已有的类的定义作为基础建立新类的定义技术。

广义的说,继承是指能够直接获得已有的性质和特征,而不必重复定义它们,所以说继承是指类之间共享属性和操作的机制。

Biology = { birth = "abc", weight = 1, speed = 0 }

-- 创建对象实例
function Biology:new(o)
    o = o or {}
	setmetatable(o, self)
	self.__index = self
	return o
end

-- 函数 :Eat
function Biology:Eat(value)
    self.weight = self.weight + value
	print("Biology Eat:"..self.weight)
end

-- 函数 .Run
function Biology.Run(self, value)
    self.speed = value
    print("Biology.Run:"..value)
end

Animation = Biology:new(nil)

-- 派生类方法
function Animation:new(o)
    o = o or Biology:new(o)
	setmetatable(o, self)
    self.__index = self
    return o
end

-- Animation 从 Biology 继承,可以调用到 Biology 的属性和方法
print("Animation.weight:"..Animation.weight)
-- 输出:Animation.weight:1

Animation.weight = 200
print("Animation.weight:"..Animation.weight)
-- 输出:Animation.weight:200

print("Biology.weight:"..Biology.weight)
-- 输出iology.weight:1

-- Animation.weight 改变值,不影响 Biology.weight

Animation:Eat(10)
print("Animation.weight:"..Animation.weight)
-- 输出:Animation.weight:210

-- 创建类实例
local animation_1 = Animation:new(nil)
-- 创建类实例
local animation_2 = Animation:new(nil)
-- 此时 Animation: 的 weight 已经赋值为 210
-- animation_1、animation_2 此时的属性值跟 Animation中属性值是相同的

print("animation_1.weight:"..animation_1.weight)
-- 输出:animation_1.weight:210

print("animation_2.weight:"..animation_2.weight)
-- 输出:animation_2.weight:210

animation_1:Eat(100)
-- 输出:Biology Eat:310

animation_2:Eat(200)
-- 输出:Biology Eat:410

print("animation_1.weight:"..animation_1.weight)
-- 输出:animation_1.weight:310

print("animation_2.weight:"..animation_2.weight)
-- 输出:animation_2.weight:410

-- 函数重写,在 Animation 类中重写函数
function Animation:Eat(value)
    self.weight = self.weight + value * 2
	print("Animation Eat:"..self.weight)
end

-- 函数重写,在 Animation 类中重写函数
function Animation.Run(self, value)
    self.speed = value * 2
    print("Animation.Run:"..self.speed)
end

animation_1:Eat(100)
-- 输出:Animation Eat:510

animation_2.Run(animation_2, 10)
-- 输出:Animation.Run:20

Animation 继承自 Biology
Animation 可以访问 Biology 的属性和函数
function Animation:Eat(value) 也可以重写父类函数

当 Animation 调用函数的时候,如果自己没有定义,通过元表 __index 方法访问父类的方法

Animation 也可以定义派生类方法
function Animation:new(o)

创建类实例
local animation_1 = Animation:new(nil)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值