0
0
Kotlinprogramming~3 mins

Why Abstract classes and methods in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write shared code once and make sure every related class follows your rules perfectly?

The Scenario

Imagine you want to create different types of vehicles like cars and bikes. You try to write separate code for each vehicle, repeating similar parts like starting the engine or stopping. It gets messy and confusing fast.

The Problem

Writing the same code again and again wastes time and causes mistakes. If you want to change how all vehicles start, you must update every single class separately. This is slow and error-prone.

The Solution

Abstract classes let you write shared code once and say "Hey, subclasses must fill in these missing parts." Abstract methods are like empty promises that subclasses must complete. This keeps your code clean and organized.

Before vs After
Before
class Car {
    fun start() { /* start engine */ }
}
class Bike {
    fun start() { /* start engine */ }
}
After
abstract class Vehicle {
    abstract fun start()
}
class Car : Vehicle() {
    override fun start() { /* start car engine */ }
}
class Bike : Vehicle() {
    override fun start() { /* start bike engine */ }
}
What It Enables

It enables you to build a clear blueprint for related classes, ensuring they share common behavior while customizing details.

Real Life Example

Think of a game where different characters have unique attacks. An abstract class can define the attack method, and each character class decides how to attack.

Key Takeaways

Abstract classes provide a common base with shared code.

Abstract methods force subclasses to implement specific behavior.

This approach reduces repeated code and improves organization.