基于lua语言实现面向对象编程

-- 使用表实现面向对象里类的定义
Person = {name="",age=0}
function Person:eat( food )
    print(self.name.." is eating "..food)
end
-- 创建类的构造方法
function Person:new(name,age)
    local t = {name=name,age=age}
    setmetatable(t,{__index=self})
    return t
end

-- 类的实例化和类方法的调用
p1 = Person:new("navy",18)
p1:eat("apple")
p2 = Person:new("summer",19)
p2:eat("pear")

-- 类的继承
Student = Person:new()
function Student:read()
    print(self.name.." is reading a book")
end
s = Student:new("summernavy",18)
s:read()


Teacher = Person:new()
function Teacher:teach(course)
    print(self.name.." is teaching "..course)
end
t = Teacher:new("navysummer",28)
t:teach("English")

 

上一篇:[C++]1.14 运算符重载


下一篇:JAVA---继承性