What is Abstract Class in Kotlin: Definition and Usage
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.
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... }
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 classcannot 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.