Kotlin Interfaces


Kotlin Interfaces – Custom Behavior Contracts

An interface in Kotlin defines a set of rules or actions that a class must follow, without giving the actual working details.

Think of it like a blueprint: it lists what should be done, but not how.


Declaring an Interface

interface Vehicle {     
         fun drive()     
         fun stop() 
} 

Vehicle interface just says any class using it must have drive() and stop() methods.


Implementing an Interface

class Car : Vehicle {     
         override fun drive() {         
                println("Car is moving")     
          }      
          
         override fun stop() {         
               println("Car has stopped")     
         } 
} 

The Car class fulfills the contract by writing its own version of the methods.


Multiple Interfaces? No Problem!

Kotlin supports multiple interfaces:

interface Electric {     
      fun charge() 
}  

class Tesla : Vehicle, Electric {     
           override fun drive() = println("Tesla zooms silently")     
           override fun stop() = println("Tesla halts with regen brakes")     
           override fun charge() = println("Charging Tesla battery") 
} 

A class can combine behaviors from different interfaces.

Feature Interface Class
Can hold state? No (mostly) Yes
Method body? Optional Yes (always)
Multiple allowed? Yes (many) No (only one)

Why Use Interfaces?

  • Promote reusability
  • Improve flexibility
  • Encourage clean structure
  • Useful for polymorphism

Prefer Learning by Watching?

Watch these YouTube tutorials to understand KOTLIN Tutorial visually:

What You'll Learn:
  • 📌 #32 Kotlin Tutorial | Interface
  • 📌 How to Implement an Interface in Kotlin
Previous Next