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.
An interface is a collection of abstract methods and properties that a class must implement. It defines what a class should do, not how.
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
Kotlin allows you to provide a default implementation in an interface. Classes implementing the interface can reuse it or override it if needed.
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
interface Flyer {
val speed: Int
get() = 100 // Computed property
}
class Jet : Flyer {
// Uses speed = 100 from interface getter
}
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
| 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) |
super<InterfaceName>.method() to resolve conflicts.