interface
The kotlin interface, similar to Java 8, uses the interface keyword to define the interface, allowing methods to have default implementations:
interface MyInterface {
fun bar() // not implemented
fun foo() { //implemented
// Optional method body
println("foo")
}
}
implement interface
A class or object can implement one or more interfaces
example:
interface MyInterface {
fun bar()
fun foo() {
// optional function
println("foo")
}
}
class Child : MyInterface {
override fun bar() {
println("bar")
}
}
Properties in the interface
The attribute in the interface can only be abstract, and initialization value is not allowed. The interface will not save the property value. When implementing the interface, the property must be rewritten
(ๆฅๅฃไธญ็ๅฑๆงๅช่ฝๆฏๆฝ่ฑก็๏ผไธๅ
่ฎธๅๅงๅๅผ๏ผๆฅๅฃไธไผไฟๅญๅฑๆงๅผ๏ผๅฎ็ฐๆฅๅฃๆถ๏ผๅฟ
้กป้ๅๅฑๆง)
example:
interface MyInterface {
var name:String //name , abstract
fun bar()
fun foo() {
// ๅฏ้็ๆนๆณไฝ
println("foo")
}
}
class Child : MyInterface {
override var name: String = "runoob" //override name
override fun bar() {
println("bar")
}
}
override function
When implementing multiple interfaces, you may encounter the problem that the same method inherits multiple implementations. For example:
interface A {
fun foo() { print("A") } // implemented
fun bar() // abstract, not implemented
}
interface B {
fun foo() { print("B") } // implemented
fun bar() { print("bar") } // implemented
}
class C : A {
override fun bar() { print("bar") } // override
}
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 d = D()
d.foo();
d.bar();
}
output:
ABbar
Top comments (0)