Menu
Coddy logo textTech

최종 OOP 점검

Coddy Lua 여정의 객체 지향 프로그래밍 (Object Oriented Programming) 섹션에 포함된 레슨. 70개 중 70번째.

challenge icon

챌린지

쉬움

Lua에서 OOP에 대해 배운 모든 내용을 함께 적용해 봅시다! 상속, 명명 convention을 통한 캡슐화, 그리고 선택적 기능을 위한 mixin을 보여 주는 차량 시스템을 구축하게 됩니다.

코드를 다섯 개의 파일로 구성합니다:

  • Vehicle.lua: 모든 차량의 Base class입니다. 각 차량에는 name과 private convention을 따르는 _speed(0으로 초기화됨)가 있습니다. :getName() getter, :getSpeed() getter, 그리고 음수 값을 거부하는 :setSpeed(value) setter를 포함하세요(음수이면 Speed cannot be negative를 출력하고 값을 변경하지 않음). "{name} moving at {speed}"를 반환하는 :describe() method를 추가하세요.
  • Refuelable.lua: 연료 관련 behavior를 포함하는 mixin table입니다. self._fuel에 더하는 :refuel(amount) method와 현재 연료 level을 반환하는 :getFuel() method를 포함하세요.
  • Car.lua: Vehicle을 Inherits하며 Refuelable mixin을 사용합니다. constructor는 name을 받아 _fuel을 0으로 초기화합니다. "{name} moving at {speed}, fuel: {fuel}"을 반환하도록 :describe()를 재정의하세요. Car에 연료 기능을 제공하도록 Refuelable mixin을 Apply하세요.
  • Bicycle.lua: Vehicle만 Inherits합니다. 연료 기능은 필요하지 않습니다. constructor는 name만 받습니다. Bicycle은 수정 없이 inherited :describe() method를 사용합니다.
  • main.lua: everything을 함께 구성합니다! inputs를 바탕으로 Car와 Bicycle을 Create하고, 서로 다른 기능을 시연하며, 공통된 차량 behavior를 공유하면서도 distinct features를 가지는 방식을 보여 주세요.

네 개의 inputs를 받습니다:

  1. Car name
  2. Bicycle name
  3. 두 차량 모두에 설정할 Speed(숫자)
  4. Car에 더할 fuel amount(숫자)

main file에서 다음을 수행하세요:

  1. given names로 Car와 Bicycle을 Create
  2. third input을 사용하여 두 차량의 Speed를 설정
  3. fourth input으로 Car에 연료를 보충
  4. Car의 description을 출력
  5. Bicycle의 description을 출력

예를 들어 inputs가 Sedan, Mountain Bike, 60, 45라면 출력은 다음과 같아야 합니다:

Sedan moving at 60, fuel: 45
Mountain Bike moving at 60

inputs가 Sports Car, Road Bike, 120, 80이라면 출력은 다음과 같아야 합니다:

Sports Car moving at 120, fuel: 80
Road Bike moving at 120

이 challenge는 상속이 shared behavior(두 차량 모두 움직일 수 있음)를 제공하고, mixin이 optional capabilities(연료가 필요한 것은 Car뿐임)를 추가하며, 캡슐화가 data integrity를 보호하는 방식(Speed validation)을 보여 줍니다. 설계에서 각 기법은 서로 다른 purpose를 수행합니다!

직접 해보기

-- main.lua: 모든 것을 하나로 모으기

local Car = require('Car')
local Bicycle = require('Bicycle')

-- 입력 읽기
local carName = io.read()
local bicycleName = io.read()
local speed = tonumber(io.read())
local fuelAmount = tonumber(io.read())

-- TODO: 주어진 이름으로 자동차 생성하기

-- TODO: 주어진 이름으로 자전거 생성하기

-- TODO: 두 차량 모두에 속도 설정하기

-- TODO: 연료량으로 자동차에 연료 보충하기

-- TODO: 자동차의 설명 출력하기

-- TODO: 자전거의 설명 출력하기

객체 지향 프로그래밍 (Object Oriented Programming)의 모든 레슨

직접 연습해 보세요: 온라인 Lua 컴파일러