[Kotlin] 상속 (abstract, interface)

유존돌돌이·2023년 3월 21일
0

Kotlin

목록 보기
2/10
post-thumbnail

final : override를 할 수 없게 한다. default
open : override를 열어 준다.
abstract : 반드시 override 해야한다.
override : 상위 타입을 오버라이드 하고 있다.

Abstract class

abstract class Animal(
    protected val species: String,
    // 프로퍼티를 오바라이드 할떈 open은 붙여줘야 한다.
    protected open val legCount: Int
) {
    abstract fun move()
}

Interface

interface Flyable {
    fun act() { println("훨훨") }
}
interface Swimmable {
    fun act() { println("어푸어푸") }
}

Class

class Cat(species: String) : Animal(species, 4) {

    override fun move() {
        println("고양이가 사뿐 사뿐 걸어가")
    }

}
class penguin(
    species: String,
    private val wingCount: Int = 2) : Animal(species, 2), Swimmable, Flyable {

    // Abstract
    // LegCount override
    override val legCount: Int
        get() = super.legCount + this.wingCount

    override fun move() {
        println("펭귄이 움직입니다~ 꿱꿱")
    }

    // Interface
    override fun act() {
        // 인터페이스 override (super<타입>.함수)
        super<Swimmable>.act()
        super<Flyable>.act()
    }

}

0개의 댓글