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.
Interface declaration and implementation in 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.
Drivable with one function. Car class implements it by providing the drive function.interface Drivable { fun drive() } class Car : Drivable { override fun drive() { println("Car is driving") } }
Person class implements it by overriding the property in the constructor.interface Named { val name: String } class Person(override val name: String) : Named
ConsoleLogger class uses the default log method without extra code.interface Logger { fun log(message: String) { println("Log: $message") } } class ConsoleLogger : Logger
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.
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() }
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.
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.