세상을 더 좋게

[Kotlin] Interface 본문

Kotlin

[Kotlin] Interface

나는SOU 2022. 2. 11. 21:57

인터페이스는 클래스를 통해 구현된다.

Example1. Runtime polymorphism 구현하기
open class Instrument {
    open fun play() {
        println("Instrument.play()")
    }
}

class Wind : Instrument() {
    override fun play() {
        println("Wind.play()")
    }
}

class Stringed : Instrument() {
    override fun play() {
        println("Stringed.play()")
    }
}

class Percussion : Instrument() {
    override fun play() {
        println("Percussion.play()")
    }
}

fun main() {
    val arr: Array<Instrument> = arrayOf(Wind(), Stringed(), Percussion())
    for (instrument in arr) {
        instrument.play()
    }
}
/*결과:
Wind.play()
Stringed.play()
Percussion.play()
*/

 

원래는 위와 같이 Instrument라는 클래스의 play 메소드를 사용하기 위해 각 클래스들이 Instrument 클래스를 상속받아서 그 메소드를 구현해야 한다. 하지만 Instrument 클래스의 play 메소드는 결국 사용되지 않는 더미 함수이다. 이런 기능을 그대로 유지하면서 이런 불필요한 더미를 제거할 수 있는 방식이 바로 Interface의 활용이다.

 

Example2. interface 활용하기
interface Instrument {
    fun play()
}

class Wind : Instrument {
    override fun play() {
        println("Wind.play()")
    }
}

class Stringed : Instrument {
    override fun play() {
        println("Stringed.play()")
    }
}

class Percussion : Instrument {
    override fun play() {
        println("Percussion.play()")
    }
}

fun main() {
    val arr: Array<Instrument> = arrayOf(Wind(), Stringed(), Percussion())
    for (instrument in arr) {
        instrument.play()
    }
}
/*결과:
Wind.play()
Stringed.play()
Percussion.play()
*/

 

위의 코드를 보면 더미 메소드의 구현 부분이 사라진 것을 알 수 있다. 하지만 Interface는 객체는 생성할 수 없기에 소위 껍데기만 놔두고 안의 객체를 구현하는 것은 상속받은 클래스들이 구현을 해야한다. 그래서 첫문장에서 Interface는 클래스를 통해 구현된다고 한 것이다.

 

함수뿐만이 아니라 var/val와 같은 프로퍼티도 구현할 수 있다. 하지만 초기화는 해줄 수 없다.

 

Example3. interface 정의
interface Instrument {
    fun play()
    val line:Int
    var playtime:Int
}

 

예시 코드 참고: https://medium.com/depayse/kotlin-%ED%81%B4%EB%9E%98%EC%8A%A4-6-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-interface-%EC%B6%94%EC%83%81-%ED%81%B4%EB%9E%98%EC%8A%A4-abstract-class-ed57aeecb9ce

 

'Kotlin' 카테고리의 다른 글

[Kotlin] by  (0) 2022.02.12