lua学习笔记18(面相对象之多态)

Lua 复制代码
print("*****************************面相对象多态*******************************")
--相同方法不同执行逻辑
object={}
object.id=1
function object:new()
	local obj={}
	self.__index=self 
	setmetatable(obj,self)
	return obj
end
function object:subClass(className)
	_G[className]={}
	local obj=_G[className] 
	self.__index=self
	obj.base=self--定义一个子类可以使用父类的方法
	setmetatable(obj,self)
end
print("******************************")
object:subClass("GameObject")
GameObject.posX=0
GameObject.posY=0
function GameObject:move()
	self.posX=self.posX+1
	self.posY=self.posY+1
	print(self.posX)
	print(self.posY)
end

GameObject:subClass("player")
function player:move()
	--self.base:move()
	--base指的是gameobject表
	--这种方法调用相当于把基类作为第一个参数传入了方法中
    self.base.move(self)--如果要执行父类的逻辑 不要直接使用冒号 要通过.的方式自己传入一个参数
end
local p1=player:new()
p1:move()
local p2=player:new()
p2:move()
p2:move()
p2:move()
print("*******************自己实现****************************")
object:subClass("atm")--定义了一个atm
atm.age=114514
atm.start=m78
function atm:move()
	 print("飞行")
end
function atm:hit()
	 print("我受伤了")
end
atm:subClass("textatm")--textatm继承atm类
function textatm:move(x)--重写move()方法
    if x==1 then
    self.base.move(self)--这样写的话当要使用父类的方法的时候就传入一个1,否者就是执行自己的方法
    else
    print("我还不会飞行")
    end
end
local p3=textatm:new()
--p3:move(1)--这样就会执行父类的方法
p3:move()
p3:hit()

atm:subClass("bigatm")
function bigatm:move()--重写move()方法
    print("我是超人我随便飞")
end
local p4=bigatm:new()
p4:move()

local p5=bigatm:new()
p5:move()

输出

相关推荐
985小水博一枚呀2 小时前
【AI大模型学习路线】第二阶段之RAG基础与架构——第七章(【项目实战】基于RAG的PDF文档助手)技术方案与架构设计?
人工智能·学习·语言模型·架构·大模型
FakeOccupational3 小时前
计算机科技笔记: 容错计算机设计05 n模冗余系统 TMR 三模冗余系统
笔记·科技
hello1114-4 小时前
Redis学习打卡-Day3-分布式ID生成策略、分布式锁
redis·分布式·学习
小Tomkk4 小时前
2025年PMP 学习二十 第13章 项目相关方管理
学习·pmp·项目pmp
独行soc4 小时前
2025年渗透测试面试题总结-百度面经(题目+回答)
运维·开发语言·经验分享·学习·面试·渗透测试·php
海棠蚀omo5 小时前
C++笔记-红黑树
开发语言·c++·笔记
ysy16480672395 小时前
03算法学习_977、有序数组的平方
学习·算法
FAREWELL000755 小时前
Unity学习总结篇(1)关于各种坐标系
学习·unity·c#·游戏引擎
龙湾开发5 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 12.曲面细分
c++·笔记·学习·3d·图形渲染
霸王蟹6 小时前
React中巧妙使用异步组件Suspense优化页面性能。
前端·笔记·学习·react.js·前端框架