Interfaces in Kotlin are powerful tools for defining contracts between different parts of your code. They play a crucial role in achieving abstraction and polymorphism in object-oriented programming.
An interface in Kotlin is a blueprint of a class that specifies a set of abstract methods and properties that a class must implement. It defines a common behavior that can be shared among multiple classes, regardless of their inheritance hierarchy.
To define an interface in Kotlin, use the interface
keyword followed by the interface name. Here's a simple example:
interface Drawable {
fun draw()
val color: String
}
In this example, Drawable
is an interface with an abstract method draw()
and an abstract property color
.
To implement an interface, a class uses the colon (:) followed by the interface name. Here's how you can implement the Drawable
interface:
class Circle : Drawable {
override fun draw() {
println("Drawing a circle")
}
override val color: String = "Red"
}
Kotlin allows you to provide default implementations for interface methods. This feature enhances code reusability and flexibility. Here's an example:
interface Clickable {
fun click()
fun showOff() = println("I'm clickable!")
}
class Button : Clickable {
override fun click() = println("Button clicked")
}
In this case, the showOff()
method has a default implementation, so classes implementing Clickable
don't need to override it unless they want to provide a different behavior.
Interfaces in Kotlin can contain abstract properties or properties with accessors. Implementing classes must provide the property implementation. For example:
interface Vehicle {
val wheelCount: Int
val description: String
get() = "A vehicle with $wheelCount wheels"
}
class Car : Vehicle {
override val wheelCount = 4
}
Interfaces in Kotlin provide a powerful mechanism for defining contracts and achieving polymorphism. They offer flexibility through features like default method implementations and properties, making them an essential tool in Kotlin programming. As you continue your Kotlin journey, explore how interfaces can be combined with other concepts like Kotlin Inheritance and Kotlin Generics to create more robust and flexible code structures.