0
0
Kotlinprogramming~5 mins

Interface declaration and implementation in Kotlin

Choose your learning style9 modes available
Introduction

An interface lets you define a set of actions that different classes can share. It helps organize code by saying what actions are possible, without saying how they work.

When you want different classes to follow the same rules or actions.
When you want to write code that works with many types of objects in the same way.
When you want to separate what something does from how it does it.
When you want to make your code easier to change or add new features later.
Syntax
Kotlin
interface InterfaceName {
    fun action1()
    fun action2(): ReturnType
    // properties can also be declared
    val propertyName: Type
}

class ClassName : InterfaceName {
    override fun action1() {
        // implementation
    }
    override fun action2(): ReturnType {
        // implementation
    }
    override val propertyName: Type = value
}

Use interface keyword to declare an interface.

Classes use : to say they implement an interface and must provide all its functions and properties.

Examples
Simple interface Drivable with one function. Car class implements it by providing the drive function.
Kotlin
interface Drivable {
    fun drive()
}

class Car : Drivable {
    override fun drive() {
        println("Car is driving")
    }
}
Interface with a property. Person class implements it by overriding the property in the constructor.
Kotlin
interface Named {
    val name: String
}

class Person(override val name: String) : Named
Interface with a default function implementation. ConsoleLogger class uses the default log method without extra code.
Kotlin
interface Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}

class ConsoleLogger : Logger
Sample Program

This program defines an Animal interface with a sound function. Dog and Cat classes implement it with their own sounds. The main function creates objects and calls their sounds.

Kotlin
interface Animal {
    fun sound()
}

class Dog : Animal {
    override fun sound() {
        println("Woof!")
    }
}

class Cat : Animal {
    override fun sound() {
        println("Meow!")
    }
}

fun main() {
    val dog: Animal = Dog()
    val cat: Animal = Cat()
    dog.sound()
    cat.sound()
}
OutputSuccess
Important Notes

Interfaces cannot hold state (no backing fields), only abstract properties or methods with default implementations.

Classes must use override keyword to implement interface members.

Interfaces help write flexible and reusable code by focusing on what actions are possible.

Summary

Interfaces define a contract of functions and properties without implementation details.

Classes implement interfaces by providing the actual code for the functions and properties.

This helps organize code and allows different classes to be used interchangeably.