Interfaces let you define a contract for classes. Default implementations let you add common behavior so classes don't have to write the same code again.
0
0
Interface with default implementations in Kotlin
Introduction
When you want multiple classes to share some common behavior but still have their own unique parts.
When you want to add new functions to an interface without breaking existing classes.
When you want to provide a basic version of a function that classes can use or override.
When you want to keep code clean by avoiding repeating the same code in many classes.
Syntax
Kotlin
interface InterfaceName { fun functionName() { // default implementation } }
Functions inside interfaces can have a body, which is the default implementation.
Classes that implement the interface can use the default or provide their own version.
Examples
This interface has a greet function with a default message.
Kotlin
interface Greeter { fun greet() { println("Hello from default!") } }
This class uses the default greet function from Greeter.
Kotlin
class Person : Greeter { // Uses default greet() }
This class provides its own greet function, replacing the default.
Kotlin
class Robot : Greeter { override fun greet() { println("Beep boop, hello!") } }
Sample Program
This program shows an interface Speaker with a default speak function. Human uses the default speak, while Parrot overrides it.
Kotlin
interface Speaker { fun speak() { println("Speaking in a normal voice.") } } class Human : Speaker { // Uses default speak() } class Parrot : Speaker { override fun speak() { println("Squawk! Hello!") } } fun main() { val person = Human() val bird = Parrot() person.speak() // Calls default implementation bird.speak() // Calls overridden implementation }
OutputSuccess
Important Notes
Default implementations help avoid repeating code in every class.
If a class overrides a function, its version is used instead of the default.
Interfaces can have multiple functions with or without default implementations.
Summary
Interfaces define what functions a class should have.
Default implementations provide a basic function body inside interfaces.
Classes can use or override these default functions as needed.