In Kotlin, an interface defines a contract for classes that implement it. Interfaces can contain methods and properties, but unlike abstract classes, they canβt hold state. However, they allow a class to implement multiple interfaces, enabling more flexible designs.
Letβs explore how to work with interfaces in Kotlin!
An interface is a collection of abstract methods and properties. Classes can implement interfaces to provide specific behavior for these methods. Kotlin interfaces can have both abstract and concrete methods (methods with implementations).
In Kotlin, an interface is defined using the interface
keyword.
interface Animal { fun speak() } class Dog : Animal { override fun speak() { println("Woof! Woof!") } } fun main() { val dog = Dog() dog.speak() // Calling the method defined in the interface }
Explanation:
speak()
method.speak()
.In Kotlin, interfaces can contain method implementations. You can define default behavior for methods in an interface, which can be overridden in the implementing class.
interface Animal { fun speak() fun sleep() { println("Zzz... I'm sleeping!") } } class Dog : Animal { override fun speak() { println("Woof! Woof!") } } fun main() { val dog = Dog() dog.speak() // Dog's own implementation dog.sleep() // Default method from Animal interface }
Explanation:
Animal
interface has a sleep()
method with a default implementation.speak()
method while using the default sleep()
method.One of Kotlin's powerful features is the ability for a class to implement multiple interfaces. This is particularly useful in cases where a class needs to adhere to multiple behaviors or contracts.
interface Animal { fun speak() } interface Swimmer { fun swim() } class Duck : Animal, Swimmer { override fun speak() { println("Quack! Quack!") } override fun swim() { println("The duck is swimming!") } } fun main() { val duck = Duck() duck.speak() // Implements Animal's speak duck.swim() // Implements Swimmer's swim }
Explanation:
speak()
and swim()
methods.Interfaces in Kotlin can also define properties. However, the property declarations in the interface are abstract, so classes implementing the interface must provide their own implementations of the properties.
interface Animal { val name: String fun speak() } class Dog(override val name: String) : Animal { override fun speak() { println("$name says Woof!") } } fun main() { val dog = Dog("Buddy") println("Animal Name: ${dog.name}") // Accessing property from interface dog.speak() // Calling method from interface }
Explanation:
name
.name
property and the speak()
method.Here are some interactive challenges for you to practice with interfaces:
fly()
. Implement it in classes like Bird and Airplane.area
and implement it in classes like Circle and Rectangle.work()
. Create classes Engineer and Manager that implement the interface and override the method.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!