728x90

하나의 클래스를 다른 클래스에 위임하도록 선언하여 위임된 클래스가 가지는 인터페이스 메소드를 참조 없이 호출할 수 있도록 생성해주는 기능이다.

 

interface Fruit를 구현하고 있는 class Apple이 있다면, 
Fruit에서 정의하고 있는 Apple의 모든 메소드를 클래스 GreenApple로 위임할 수 있다. 
즉, GreenApple은 Apple이 가지는 모든 Fruit의 메소드를 가지며, 이를 클래스 위임(Class delegation)이라고 한다.

interface Fruit {
    val name: String
    val color: String
    fun bite()
}
 
class Apple: Fruit {
    override val name: String
        get() = "사과"
    override val color: String
        get() = "빨간색"
 
    override fun bite() {
        print("사과 아삭~ 아삭~")
    }
}
 
// 클래스 위임 : 사용할 기능은 그대로 사용하고 새로 정의할 것만 override로 재정의
class GreenApple(
    private val apple: Apple
) : Fruit by apple {
    override val color: String
        get() = "초록색"
}

 

fun main() {
    val greenApple = GreenApple(Apple())
    println(greenApple.color)
    println(greenApple.name)
    greenApple.bite()
}

 

 

'안드로이드 > Kotlin 문법' 카테고리의 다른 글

코틀린 제네릭 공변, 반공변  (0) 2024.02.04
[코틀린] ArrayList, mutableListOf  (0) 2021.06.14
[코틀린] Inner Class  (0) 2020.08.21
[코틀린] Nested Class (중첩 클래스)  (0) 2020.08.21
코틀린 클래스  (0) 2020.05.06
블로그 이미지

Link2Me

,