「Kotlin入門」複数のインターフェースを実装するサンプル

2020年11月8日

構文
interface インターフェースA {
}
interface インターフェースB {
}
class クラス名:インターフェースA,インターフェースB{
}
使用例
1.インターフェースの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
interface A {
fun foo() { print("AA") } // 実装
fun bar() // 未実装
}
interface B {
fun foo() { print("BB") } // 実装
fun bar() { print("bar") } // 実装
}
interface A { fun foo() { print("AA") } // 実装 fun bar() // 未実装 } interface B { fun foo() { print("BB") } // 実装 fun bar() { print("bar") } // 実装 }
interface A {
    fun foo() { print("AA") }   // 実装
    fun bar()                  // 未実装
}
 
interface B {
    fun foo() { print("BB") }   // 実装
    fun bar() { print("bar") } // 実装
}

2.インターフェースの実装

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class C : A {
  // オーバーライド
override fun bar() { print("bar") }
}
class C : A {   // オーバーライド override fun bar() { print("bar") } }
class C : A {
  // オーバーライド
    override fun bar() { print("bar") }   
}

3.複数インターフェースの実装

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class D : A, B {
override fun foo() {
super<A>.foo()
super<B>.foo()
}
override fun bar() {
super<B>.bar()
}
}
fun main(args: Array<String>) {
val cft = D()
cft.foo();
cft.bar();
}
class D : A, B { override fun foo() { super<A>.foo() super<B>.foo() } override fun bar() { super<B>.bar() } } fun main(args: Array<String>) { val cft = D() cft.foo(); cft.bar(); }
class D : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }
 
    override fun bar() {
        super<B>.bar()
    }
}
 
fun main(args: Array<String>) {
    val cft =  D()
    cft.foo();
    cft.bar();
}

実行結果
AABBbar

Kotlin

Posted by arkgame