继承是面向对象中一个很重要的特性,要想在lua中实现该特性也相对比较简单,配合元表和__index
元方法,让派生类与基类形成一条链,前面我们学习了Student类,那么我们让Student类继承自Person类,看代码:
-----------------基类---------------------
Person = {};
-- 设置__index键为一张表,这个表是自己
Person.__index = Person --关键
-- 定义类型属性(相当于静态成员变量)
Person.objCount = 0;
-- 定义类方法(相当于静态成员函数)
function Person:Count( )
print ("一共有".. self.objCount.."个对象!");
end
-- 定义构造函数
function Person:Create()
Person.objCount = Person.objCount + 1;
local instance = {};
setmetatable(instance, self.prototype); --此处是关键
print( "-->",self.prototype) --这里如果是派生类Student调用,那么self就是派生类Student
return instance;
end
-- 定义类型的prototype
Person.prototype = {};
-- 设置prototype的__index元方法
Person.prototype.__index = Person.prototype;
-- 定义实例对象属性
Person.prototype.name = "";
Person.prototype.age = 0;
-- 定义实例对象方法
function Person.prototype:Init( a , n)
self.age =a;
self.name =n
end
-- 定义打印方法(使用:)
function Person.prototype:Show()
print ( "姓名:"..self.name ,"年龄:"..self.age);
end
-----------------派生类---------------------
-- 创建类型并绑定父类作为元表
Student = {};
setmetatable(Student, Person);
-- 创建prototype并绑定父类prototype作为元表
Student.prototype = { class };
Student.prototype.__index = Student.prototype;
setmetatable(Student.prototype, Person.prototype); -- 关键: instance 的元表是 Student.prototype ,Student.prototype的元表是Person.prototype
print( ">>>",Student.prototype)
-- 定义打印方法(使用:)
function Student.prototype:Show()
print ( "姓名:"..self.name ,"年龄:"..self.age , " 班级:"..self.class);
end
--------------测试-----------------------------
local stu1 = Student:Create();
stu1:Init("张三",12) --使用:方式调用
stu1.class ="一年级"
stu1:Show()
local stu2 = Student:Create();
stu2.Init(stu2,"李四",16) -- 使用.方式调用
stu2.class ="二年级"
stu2.Show(stu2)
--模拟类的静态变量、方法
print(Student.objCount)
Student:Count() --使用:方式调用
Student.Count(Student) -- 使用.方式调用
运行效果如下:
跟大家做了一张图: