Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 2525
- kotlin
- 백준1107
- dp
- 백준1476
- 18108
- 새싹
- 25083
- Android
- 기본메신저
- 사파리 월드
- safari world
- debugSymbolLevel
- 10807
- 1330
- Counting The number
- PreferenceManager
- 10926
- baekjoon
- 백준
- 10430
- 백준3085
- 개수 세기
- Class Delegation
- 코틀린
- BitMasking
- 꼬마 정민
- 파이썬
- 디버그심볼
- 브루트포스
Archives
- Today
- Total
세상을 더 좋게
[Kotlin] Interface 본문
인터페이스는 클래스를 통해 구현된다.
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
}
'Kotlin' 카테고리의 다른 글
[Kotlin] by (0) | 2022.02.12 |
---|