클래스 상속(subclassing) 예제 with Lua
Lua도 클래스 기반 객체지향 언어가 아니라 Self, Io, ECMAScript 언어들 처럼 프로토타입 기반 객체 지향 언어이다. Lua 언어에서 클래스 상속을 구현하기 위해서는 테이블과 함수가 필요하다.
아래의 소스 코드에서 inheritsFrom() 함수가 클래스 상속을 위해 구현돤 함수이다.
Lua 언어도 Java 언어 처럼 대소문자 구별을 엄격히 하므로 클래스를 선언하고 그 클래스로 객체 생성할 때 대소문자 구별을 꼭 지켜야 한다.
다음은 두 개의 클래스로 구성되어 있다.
Parent는 부모 클래스이고 Child는 Parent에서 상속 받은 자식 클래스이다.
-- Filename: testSubclassing.lua
--
-- A new inheritsFrom() function
--
function inheritsFrom( baseClass )
local new_class = {}
local class_mt = { __index = new_class }
function new_class:create(name)
local newinst = {}
self.name = name
setmetatable( newinst, class_mt )
return newinst
end
if nil ~= baseClass then
setmetatable( new_class, { __index = baseClass } )
end
-- Implementation of additional OO properties starts here --
-- Return the class object of the instance
function new_class:class()
return new_class
end
-- Return the super class object of the instance
function new_class:superClass()
return baseClass
end
function new_class:sayName()
print(self.name)
end
return new_class
end
Parent = inheritsFrom( nil ) -- pass nil because Parent has no super class
Child = inheritsFrom( Parent ) -- subclassing here
function Child:sayName() -- Override method
print("I am a chile, named as " .. self.name)
end
obj = Child:create("Dooly")
obj:sayName()
실행> lua testSubclassing.lua
I am a child, named as Dooly
LuaJava로 실행해도 된다.
실행> luajava testSubclassing.lua
I am a child, named as Dooly