요약 - 도형 계층 구조
Coddy Lua 여정의 객체 지향 프로그래밍 (Object Oriented Programming) 섹션에 포함된 레슨. 70개 중 36번째.
챌린지
쉬움완전한 shape 계층 구조를 처음부터 만들어 봅시다! 모든 shape이 상속하는 Shape parent class를 만든 다음, 각각 고유한 속성을 가지면서 공통 기능을 공유하는 Circle 및 Square child classes를 만듭니다.
코드를 네 개의 파일로 구성합니다:
Shape.lua: 모든 shape이 상속할 base class입니다. shape의 색상을 저장하는:new(color)constructor와 색상을 반환하는:getColor()method를 포함해야 합니다. 이 공통 속성 덕분에 circle이든 square이든 모든 shape은 color를 갖게 됩니다.Circle.lua: Shape을 상속하는 child class입니다.:new(color, radius)constructor는 color를 처리하기 위해 parent constructor를 호출한 다음, radius를 고유한 attribute로 추가해야 합니다. circle의 세부 정보를 출력하는:describe()method도 포함하세요.Square.lua: Shape을 상속하는 또 다른 child class입니다.:new(color, side)constructor 역시 parent constructor를 호출한 다음 side length를 저장해야 합니다. square를 위한:describe()method도 포함하세요.main.lua: 두 shape의 instance를 만들고, 고유한 속성을 유지하면서 Shape을 올바르게 상속하는 모습을 보여 주어 모든 것을 하나로 구성합니다.
두 개의 입력을 받습니다:
- Circle 데이터: 쉼표로 구분된 color와 radius (예:
blue,5) - Square 데이터: 쉼표로 구분된 color와 side length (예:
red,4)
main 파일에서 주어진 값으로 Circle과 Square를 만듭니다. 그런 다음 다음 내용을 각각 별도의 줄에 출력합니다:
- circle에서
:describe()호출 - square에서
:describe()호출 :getColor()를 사용하여 circle의 color 출력:getColor()를 사용하여 square의 color 출력
Circle의 :describe() method는 다음을 출력해야 합니다:
Circle with radius {radius}Square의 :describe() method는 다음을 출력해야 합니다:
Square with side {side}예를 들어 입력이 blue,5와 red,4라면 출력은 다음과 같아야 합니다:
Circle with radius 5
Square with side 4
blue
red이는 완전한 상속 패턴을 보여 줍니다. 두 shape 모두 Shape에서 :getColor()를 상속하며(직접 정의하지 않음), 각각 고유한 attribute와 :describe() method를 가집니다!
직접 해보기
-- main.lua: 모든 것을 한데 모으기
local Circle = require('Circle')
local Square = require('Square')
-- circle 입력 읽기 (color,radius)
local circleInput = io.read()
local circleColor, circleRadius = circleInput:match("([^,]+),([^,]+)")
circleRadius = tonumber(circleRadius)
-- square 입력 읽기 (color,side)
local squareInput = io.read()
local squareColor, squareSide = squareInput:match("([^,]+),([^,]+)")
squareSide = tonumber(squareSide)
-- TODO: 주어진 color와 radius로 Circle 인스턴스 생성
-- TODO: 주어진 color와 side로 Square 인스턴스 생성
-- TODO: circle에서 :describe() 호출
-- TODO: square에서 :describe() 호출
-- TODO: :getColor()를 사용하여 circle의 color 출력
-- TODO: :getColor()를 사용하여 square의 color 출력
객체 지향 프로그래밍 (Object Oriented Programming)의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러