What is Interface in Kotlin: Definition and Usage
interface is a blueprint that defines a set of functions and properties without implementing them. Classes can implement interfaces to provide specific behavior, allowing multiple classes to share common functionality without inheritance.How It Works
Think of an interface as a contract or a promise that a class makes. It says, "I will provide these functions," but it doesn't say how. This is like a job description that lists tasks but leaves the details to the employee.
In Kotlin, interfaces can declare functions and properties. Classes that implement the interface must provide the actual code for these functions, unless the interface already provides a default implementation. This allows different classes to share the same set of behaviors while keeping their own unique details.
Interfaces help organize code by separating what something can do from how it does it. This makes your code easier to understand and change, just like having clear roles in a team helps everyone work better together.
Example
This example shows an interface Drivable with a function drive(). Two classes, Car and Bike, implement this interface and provide their own versions of drive().
interface Drivable {
fun drive()
}
class Car : Drivable {
override fun drive() {
println("Car is driving")
}
}
class Bike : Drivable {
override fun drive() {
println("Bike is driving")
}
}
fun main() {
val car = Car()
val bike = Bike()
car.drive()
bike.drive()
}When to Use
Use interfaces when you want to define a common set of actions that different classes should perform, but the details of how they do it can vary. For example, if you have different types of vehicles, devices, or workers that share some behaviors, interfaces let you write code that works with all of them without knowing their exact type.
Interfaces are especially useful when you want to:
- Allow multiple classes to share functionality without forcing them into a strict inheritance chain.
- Design flexible and reusable code that can work with different implementations.
- Define APIs or libraries where you specify what actions are possible, letting users decide how to implement them.
Key Points
- An
interfacedefines functions and properties without full implementation. - Classes
implementinterfaces to provide specific behavior. - Interfaces can have default implementations for some functions.
- They help achieve flexible and reusable code without inheritance.
- Multiple interfaces can be implemented by a single class.