Menu
Coddy logo textTech

기본 메서드

Coddy Kotlin 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 23번째.

인터페이스 메서드는 본문을 가질 수 있습니다. 이 기본 구현은 이를 재정의하지 않는 모든 클래스에서 사용됩니다:

interface Greeter {
    val name: String
    fun greet() = "Hello, I am $name"
}
class Robot(override val name: String) : Greeter
class Pirate(override val name: String) : Greeter {
    override fun greet() = "Ahoy! $name here"
}

main 내부에서:

println(Robot("R2").greet())
println(Pirate("Anne").greet())

출력:

Hello, I am R2
Ahoy! Anne here

기본 메서드는 인터페이스의 다른 멤버를 기반으로 작성됩니다. 클래스는 다른 부분에 해당하는 몇 가지 멤버만 제공하고 나머지는 전달받습니다:

interface Priced {
    val cents: Int
    fun formatted() = "$%d.%02d".format(cents / 100, cents % 100)
    fun isAffordable(budget: Int) = cents <= budget
}
class Coffee : Priced {
    override val cents = 450
}

main 내부에서:

val c = Coffee()
println(c.formatted())
println(c.isAffordable(400))

출력:

$4.50
false

속성에는 기본 getter를 사용할 수 있지만, 인터페이스에는 뒷받침 필드가 없으므로 값을 저장할 수 없습니다. 초기화 구문이 있는 속성은 컴파일되지 않지만, 값을 계산하는 getter는 사용할 수 있습니다:

interface Box {
    val width: Int
    val height: Int
    val area: Int
        get() = width * height
    // val count = 0      // error: 인터페이스에서는 프로퍼티 초기화자가 허용되지 않습니다
}
class Tile(override val width: Int, override val height: Int) : Box

main 내부에서:

println(Tile(3, 4).area)

출력:

12

오버라이드는 여전히 기본 구현을 사용할 수 있습니다. 클래스 내부에서 super.method()는 인터페이스의 버전을 호출합니다:

interface Priced {
    val cents: Int
    fun formatted() = "$%d.%02d".format(cents / 100, cents % 100)
}
class Coffee : Priced {
    override val cents = 450
    override fun formatted() = "coffee " + super.formatted()
}

main 내부에서:

println(Coffee().formatted())

출력:

coffee $4.50
challenge icon

챌린지

쉬움

Priced 인터페이스에는 price(센트 단위)가 있습니다. $4.50을 반환하는 기본 formatted()와 가격이 예산 이하인지 반환하는 기본 isAffordable(budget)를 작성하세요. Coffee의 가격은 450이며, formatted()를 coffee $4.50으로 재정의하고 super를 통해 기본 구현을 재사용합니다. Sandwich(price)는 두 기본 구현을 모두 사용합니다.

제공된 코드는 센트 단위의 예산을 읽은 다음 coffee 또는 sandwich,650 형식의 줄을 읽습니다. 각 항목에 대해 formatted()와 yes 또는 no를 출력합니다.

작성한 코드는 Priced.kt, Coffee.kt, Sandwich.kt에 넣으세요. Main.kt에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

fun main() {
    // 제공된 입력/출력 코드: 그대로 유지하세요
    val input = generateSequence(::readLine).toList()
    val budget = input[0].toInt()
    for (line in input.drop(1)) {
        val p = line.split(",")
        val item: Priced = if (p[0] == "coffee") Coffee() else Sandwich(p[1].toInt())
        println("${item.formatted()} ${if (item.isAffordable(budget)) "yes" else "no"}")
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: Kotlin 플레이그라운드