
Interface in Kotlin
📌 Interface in Kotlin
An interface in Kotlin is a blueprint that defines a set of abstract methods and properties without any implementation. It provides a way to achieve abstraction and multiple inheritance. Classes that implement an interface must provide concrete implementations of its methods.
✅ 1. Key Features of Interfaces in Kotlin
Contains abstract methods (without implementation).
Can contain default method implementations using
fun
with a body.Supports properties (with or without implementation).
Supports multiple inheritance using interfaces.
Cannot store state (no instance variables).
✅ 2. Defining an Interface
You can define an interface using the interface
keyword.
📌 Example:
fun () // Abstract function fun () { println("Animal is eating") }}
sound()
→ Abstract method (no body).eat()
→ Method with a default implementation.
✅ 3. Implementing an Interface
A class implements an interface using the :
operator and provides the body for abstract methods using override
.
📌 Example:
interface Animal { fun () fun () { println("Animal is eating") }}class Dog : Animal { override fun () { println("Dog barks") }}fun () { val dog = Dog() dog.sound() dog.eat()}
Output:
Dog barksAnimal is eating
Dog
provides its own implementation for thesound()
method.The
eat()
method uses the default implementation from the interface.
✅ 4. Multiple Interfaces
A class can implement multiple interfaces in Kotlin.
📌 Example:
interface Animal { fun ()}interface Pet { fun () { println("Pet is playing") }}class Cat : Animal, Pet { override fun () { println("Cat meows") }}fun () { val cat = Cat() cat.sound() cat.play()}
Output:
Cat meowsPet is playing
Kotlin supports multiple inheritance of interfaces.
✅ 5. Interface Properties
Interfaces can define properties.
If the property has no value, the implementing class must provide it.
If the property has a default value, it can be inherited.
📌 Example:
interface Vehicle { val name: String val wheels: Int get() = 4}class Car : Vehicle { override val name = "Car"}fun () { val car = Car() println("${car.name} has Car has 4 wheels
wheels
has a default value (4
) in the interface.name
is provided by theCar
class.
✅ 6. Resolving Conflicts in Interfaces
If two interfaces provide methods with the same name and a class implements both, you must override the conflicting method.
📌 Example:
interface A { fun () { println("Display from A") }}interface B { fun () { println("Display from B") }}class C : A, B { override fun () { super<A>.display() // Resolving conflict }}fun main() { val obj = C() obj.display()}
Output:
Display from A
super<A>.display()
specifies which interface's method to call.
✅ 7. Conclusion
Use interfaces to define a contract with abstract methods and optional default implementations.
Multiple interfaces can be implemented by a single class.
Resolve conflicts using super<InterfaceName>.method().
Interfaces provide a way to achieve multiple inheritance in Kotlin.