0
0
Kotlinprogramming~3 mins

Why Interface declaration and implementation in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one plan and have many different characters follow it perfectly without confusion?

The Scenario

Imagine you are building a game where different characters can perform actions like jump, run, or attack. Without a clear plan, you write separate code for each character, repeating similar actions again and again.

The Problem

This manual way is slow and confusing. If you want to add a new character or change an action, you must update many places. Mistakes happen easily, and your code becomes messy and hard to fix.

The Solution

Interfaces let you define a clear list of actions that any character must have. You write the action rules once, then each character promises to follow them. This keeps your code neat, easy to update, and everyone knows what to expect.

Before vs After
Before
class Knight {
  fun attack() { /* code */ }
}
class Archer {
  fun attack() { /* code */ }
}
After
interface Fighter {
  fun attack()
}
class Knight : Fighter {
  override fun attack() { /* code */ }
}
class Archer : Fighter {
  override fun attack() { /* code */ }
}
What It Enables

Interfaces make your code flexible and organized, so you can add new features easily without breaking what already works.

Real Life Example

Think of a remote control that works with many devices. The remote defines buttons (interface), and each device implements how those buttons work, so you can control TVs, music players, or lights with the same remote.

Key Takeaways

Interfaces define a clear set of actions to follow.

They help avoid repeating code and reduce errors.

They make adding new features easier and safer.