Kotlin Interfaces - Defining and Implementing
Interfaces are a crucial part of object-oriented programming and are used to define contracts that classes must adhere to. In Kotlin, you can both define and implement interfaces, providing a flexible way to structure your code. In this guide, we'll explore how to work with interfaces in Kotlin.
Defining an Interface
You can define an interface in Kotlin using the interface
keyword. Here's an example:
interface Shape {
fun area(): Double
fun perimeter(): Double
}
The Shape
interface defines two abstract methods: area
and perimeter
.
Implementing an Interface
To implement an interface, you create a class that implements the methods defined in the interface. Here's an example:
class Circle(val radius: Double) : Shape {
override fun area(): Double {
return Math.PI * radius * radius
}
override fun perimeter(): Double {
return 2 * Math.PI * radius
}
}
The Circle
class implements the Shape
interface by providing concrete implementations of the area
and perimeter
methods.
Using Interfaces
You can create instances of classes that implement interfaces and use them as instances of the interface type:
val shape: Shape = Circle(5.0)
val circleArea = shape.area()
val circlePerimeter = shape.perimeter()
Multiple Interfaces
A class can implement multiple interfaces, allowing you to define contracts from multiple sources:
interface Drawable {
fun draw()
}
class ShapeWithDrawing(val sides: Int) : Shape, Drawable {
override fun area(): Double {
// Area calculation
}
override fun perimeter(): Double {
// Perimeter calculation
}
override fun draw() {
// Drawing code
}
}
Conclusion
Interfaces in Kotlin provide a powerful way to define contracts and achieve code modularity. You can define interfaces with abstract methods and then implement those interfaces in your classes. This allows for flexibility and code reusability, making Kotlin a versatile and expressive programming language.
Happy coding!