0
0
KotlinConceptBeginner · 3 min read

What is Abstract Class in Kotlin: Definition and Usage

In Kotlin, an abstract class is a class that cannot be instantiated directly and can contain abstract methods without implementation. It serves as a blueprint for other classes to inherit and provide specific implementations for its abstract members.
⚙️

How It Works

Think of an abstract class as a blueprint for a house. You can't live in the blueprint itself, but it shows how the house should be built. Similarly, an abstract class in Kotlin defines properties and functions that subclasses must implement or can override.

It can have both fully defined methods and abstract methods (without body). You cannot create an object directly from an abstract class, but you can create objects from classes that inherit from it and provide implementations for the abstract parts.

💻

Example

This example shows an abstract class Animal with an abstract function makeSound(). The subclasses Dog and Cat provide their own implementations.

kotlin
abstract class Animal {
    abstract fun makeSound()

    fun sleep() {
        println("Sleeping...")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Woof!")
    }
}

class Cat : Animal() {
    override fun makeSound() {
        println("Meow!")
    }
}

fun main() {
    val dog = Dog()
    dog.makeSound()  // Woof!
    dog.sleep()      // Sleeping...

    val cat = Cat()
    cat.makeSound()  // Meow!
    cat.sleep()      // Sleeping...
}
Output
Woof! Sleeping... Meow! Sleeping...
🎯

When to Use

Use an abstract class when you want to define a common template for related classes but don't want to allow creating objects of the base class itself. It is useful when multiple classes share some behavior but also have their own specific implementations.

For example, in a game, you might have an abstract class Character with abstract methods like attack() and defend(). Different character types like Warrior and Mage implement these methods differently.

Key Points

  • An abstract class cannot be instantiated directly.
  • It can contain both abstract and concrete methods.
  • Subclasses must override abstract methods.
  • Useful for sharing common code and enforcing a contract for subclasses.

Key Takeaways

An abstract class in Kotlin defines a template with abstract and concrete methods but cannot be instantiated.
Subclasses must provide implementations for all abstract methods of the abstract class.
Use abstract classes to share common code and enforce method implementation in related classes.
Abstract classes help organize code when multiple classes share behavior but differ in details.