개발 일기

Interface ? 본문

컴퓨터 언어/kotlin

Interface ?

이건욱

Kotlin은 Interface을 제공합니다.

 

Interface는 추상화 메소드를 포함할수 있습니다.

추상화 클래스와 다른점은 상태를 저장할수 없습니다.

속성을 가질수 있지만 추상화를 하거나 또는 접근이 가능한 구현을 제공해야합니다.

 

예시 :)

interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}

구현 :)

class Child : MyInterface {
    override fun bar() {
        // body
    }
}

 

속성 :)

interface MyInterface {
    val prop: Int // abstract

    val propertyWithImplementation: String
        get() = "foo"

    fun foo() {
        print(prop)
    }
}

class Child : MyInterface {
    override val prop: Int = 29
}

 

상속 :)

interface Named {
    val name: String
}

interface Person : Named {
    val firstName: String
    val lastName: String
    
    override val name: String get() = "$firstName $lastName"
}

data class Employee(
    // implementing 'name' is not required
    override val firstName: String,
    override val lastName: String,
    val position: Position
) : Person

상속 충돌 :)

interface A {
    fun foo() { print("A") }
    fun bar()
}

interface B {
    fun foo() { print("B") }
    fun bar() { print("bar") }
}

class C : A {
    override fun bar() { print("bar") }
}

class D : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        super<B>.bar()
    }
}

'컴퓨터 언어 > kotlin' 카테고리의 다른 글

Extensions ?  (0) 2020.04.23
Visibility Modifiers  (0) 2020.04.20
Properties and Fields ?  (0) 2020.04.16
class ?  (0) 2020.04.15
if , when , for , while ?  (0) 2020.04.12
Comments