Kotlin Interface
# Kotlin Interfaces
Kotlin interfaces are similar to Java 8, using the `interface` keyword to define an interface, and allowing methods to have default implementations:
```kotlin
interface MyInterface {
fun bar() // Not implemented
fun foo() { // Implemented
// Optional method body
println("foo")
}
}
### Implementing Interfaces
A class or object can implement one or more interfaces.
```kotlin
class Child : MyInterface {
override fun bar() {
// Method body
}
}
## Example
```kotlin
interface MyInterface {
fun bar()
fun foo() {
// Optional method body
println("foo")
}
}
class Child : MyInterface {
override fun bar() {
// Method body
println("bar")
}
}
fun main(args: Array) {
val c = Child()
c.foo(); c.bar();
}
The output is:
foo
bar
### Properties in Interfaces
Properties in interfaces can only be abstract, and initialization is not allowed. Interfaces do not store property values. When implementing an interface, properties must be overridden:
```kotlin
interface MyInterface {
var name: String // name property, abstract
}
class MyImpl : MyInterface {
override var name: String = "tutorial" // Override property
}
## Example
```kotlin
interface MyInterface {
var name: String // name property, abstract
fun bar()
fun foo() {
// Optional method body
println("foo")
}
}
class Child : MyInterface {
override var name: String = "tutorial" // Override property
override fun bar() {
// Method body
println("bar")
}
}
fun main(args: Array) {
val c = Child()
c.foo(); c.bar();
println(c.name)
}
The output is:
foo
bar
tutorial
* * *
## Function Overriding
When implementing multiple interfaces, you may encounter the issue of inheriting multiple implementations for the same method. For example:
## Example
```kotlin
interface A {
fun foo() { print("A") } // Implemented
fun bar() // Not implemented, no method body, abstract
}
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.foo()
super.foo()
}
override fun bar() {
super.bar()
}
}
fun main(args: Array) {
val d = D()
d.foo(); d.bar();
}
The output is:
ABbar
In the example, interfaces A and B both define methods `foo()` and `bar()`. Both implement `foo()`, and B implements `bar()`. Since C is a concrete class that implements A, it must override `bar()` and implement this abstract method.
However, if we derive D from A and B, we need to implement all methods inherited from multiple interfaces and specify how D should implement them. This rule applies to methods inheriting a single implementation (`bar()`) as well as methods inheriting multiple implementations (`foo()`).
YouTip