Interfaces & Default Methods in Kotlin

Interfaces in Kotlin define a contract for classes, specifying functions and properties that must be implemented. Unlike Java 7, Kotlin interfaces can also provide default implementations, allowing behavior reuse without requiring inheritance.

1. Why Interfaces & Default Methods Matter

2. What is an Interface?

An interface is a collection of abstract methods and properties that a class must implement. It defines what a class should do, not how.

2.1 Basic Interface Example


interface Flyable {
    fun fly()
}

class Bird : Flyable {
override fun fly() {
println("Bird is flying")
}
}

fun main() {
val bird = Bird()
bird.fly()
} 

Output:


Bird is flying
  

3. Default Methods in Interfaces

Kotlin allows you to provide a default implementation in an interface. Classes implementing the interface can reuse it or override it if needed.

3.1 Example: Default Method


interface Movable {
    fun move() {
        println("Moving by default behavior")
    }
}

class Car : Movable {
// Reuses default implementation
}

class Bike : Movable {
override fun move() {
println("Bike moves differently")
}
}

fun main() {
val car = Car()
val bike = Bike()
car.move()   // Uses default method
bike.move()  // Uses overridden method
} 

Output:


Moving by default behavior
Bike moves differently
  

4. Difference Between Interface Default Methods and Class Methods


interface Flyer {
    val speed: Int
        get() = 100  // Computed property
}

class Jet : Flyer {
// Uses speed = 100 from interface getter
} 

5. Multiple Interfaces & Conflict Resolution (Diamond Problem)

A class can implement multiple interfaces. If two interfaces have methods with the same signature, Kotlin requires you to override the method and resolve the conflict explicitly.


interface Flyer {
    fun action() = println("Flying")
}

interface Mover {
fun action() = println("Moving")
}

class Drone : Flyer, Mover {
override fun action() {
super.action()  // Call Flyer’s version
super.action()  // Call Mover’s version
println("Drone executes both actions")
}
}

fun main() {
val drone = Drone()
drone.action()
} 

Output:


Flying
Moving
Drone executes both actions
  

6. Summary Table

Concept Interface Default Method Class Method
Can provide behavior Yes Yes
Can store state (backing field) No Yes
Mandatory override Optional Optional (open/abstract)
Multiple inheritance safe? (explicit override needed if conflict) (diamond problem)

7. Technical Interview Questions

8. Key Takeaways