-- 派生类的方法 new functionRectangle:new(o,length,breadth) o = o or {} setmetatable(o, self) self.__index = self self.length = length or0 self.breadth = breadth or0 self.area = length*breadth; return o end
-- 派生类的方法 printArea functionRectangle:printArea() print("矩形面积为 ",self.area) end
Shape = {area = 0} -- 基础类方法 new functionShape:new(o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or0 self.area = side*side; return o end -- 基础类方法 printArea functionShape:printArea() print("面积为 ",self.area) end
接下来的实例,Square 对象继承了 Shape 类:
1 2 3 4 5 6 7 8
Square = Shape:new() -- Derived class method new functionSquare:new(o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end
Shape = {area = 0} -- 基础类方法 new functionShape:new(o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or0 self.area = side*side; return o end -- 基础类方法 printArea functionShape:printArea() print("面积为 ",self.area) end
Rectangle = Shape:new() -- 派生类方法 new functionRectangle:new(o,length,breadth) o = o or Shape:new(o) setmetatable(o, self) self.__index = self self.area = length * breadth return o end
-- 派生类方法 printArea functionRectangle:printArea() print("矩形面积为 ",self.area) end