0
0
Kotlinprogramming~5 mins

Multiple interface implementation in Kotlin

Choose your learning style9 modes available
Introduction

Sometimes, a class needs to do many different jobs. Multiple interface implementation lets a class promise to do all those jobs.

When a class needs to follow rules from more than one interface.
When you want to add different abilities to a class without using inheritance.
When you want to organize code by separating different behaviors into interfaces.
When you want to make your class flexible and reusable in different situations.
Syntax
Kotlin
class ClassName : Interface1, Interface2 {
    // Implement all interface methods here
}

You list interfaces after a colon : separated by commas.

You must implement all functions from all interfaces in the class.

Examples
This class Vehicle promises to do both drive and fly actions.
Kotlin
interface Drivable {
    fun drive()
}

interface Flyable {
    fun fly()
}

class Vehicle : Drivable, Flyable {
    override fun drive() {
        println("Driving on the road")
    }
    override fun fly() {
        println("Flying in the sky")
    }
}
OfficeMachine can both print and scan by implementing two interfaces.
Kotlin
interface Printable {
    fun print()
}

interface Scannable {
    fun scan()
}

class OfficeMachine : Printable, Scannable {
    override fun print() {
        println("Printing document")
    }
    override fun scan() {
        println("Scanning document")
    }
}
Sample Program

This program shows a class FileHandler that can both read and write by implementing two interfaces.

Kotlin
interface Reader {
    fun read()
}

interface Writer {
    fun write()
}

class FileHandler : Reader, Writer {
    override fun read() {
        println("Reading file contents")
    }
    override fun write() {
        println("Writing to file")
    }
}

fun main() {
    val handler = FileHandler()
    handler.read()
    handler.write()
}
OutputSuccess
Important Notes

If two interfaces have methods with the same name, you can use super<InterfaceName>.method() to specify which one to call.

Interfaces can have default method implementations, so you don't always have to override them.

Summary

Multiple interface implementation lets a class do many jobs by following many interfaces.

List interfaces separated by commas after the class name.

Implement all required methods from all interfaces in your class.