2024-06-21
This commit is contained in:
58
Writerside/topics/Interface.md
Normal file
58
Writerside/topics/Interface.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# 인터페이스
|
||||
|
||||
인터페이스는 구현된 메서드를 가질 수도 있으며, 프로퍼티를 가질 수도 있습니다. 인터페이스는 `interface` 를 사용해서 선언합니다.
|
||||
|
||||
```kotlin
|
||||
interface MyInterface {
|
||||
val prop1: Int // 추상 프로퍼티
|
||||
val prop2: String // 겟터가 구현된 프로퍼티
|
||||
get() = "foo"
|
||||
fun bar()
|
||||
fun foo() {
|
||||
// 바디를 가질 수도 있습니다.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 다중 상속시 충돌 문제의 해결
|
||||
|
||||
```kotlin
|
||||
interface A {
|
||||
fun foo() { print("A") }
|
||||
fun bar()
|
||||
}
|
||||
interface B {
|
||||
fun foo() { print("B") }
|
||||
fun bar()
|
||||
}
|
||||
|
||||
class C : A, B {
|
||||
override fun foo() {
|
||||
super<A>.foo()
|
||||
super<B>.foo()
|
||||
}
|
||||
override fun bar(){
|
||||
print("C")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 함수형 인터페이스
|
||||
|
||||
함수형 인터페이스란, 하나의 추상 메서드만을 가진 인터페이스입니다. `fun interface`를 사용해서 선언합니다.
|
||||
|
||||
```kotlin
|
||||
fun interface KRunnable {
|
||||
fun invioke()
|
||||
}
|
||||
```
|
||||
|
||||
함수형 인터페이스는 람다 표현식에서 유용하게 사용됩니다.
|
||||
|
||||
```kotlin
|
||||
fun interface IntPredicate {
|
||||
fun accept(i: Int): Boolean
|
||||
}
|
||||
|
||||
val isEven = IntPredicate {it % 2 == 0 }
|
||||
```
|
||||
Reference in New Issue
Block a user