Abstract classes are a fundamental concept in Kotlin's object-oriented programming paradigm. They serve as blueprints for other classes, providing a common structure and behavior while allowing for specialized implementations.
An abstract class is a class that cannot be instantiated directly. It is designed to be subclassed, providing a common interface for a group of related classes. Abstract classes can contain both abstract and concrete methods, as well as properties.
To declare an abstract class in Kotlin, use the abstract
keyword before the class
keyword:
abstract class Shape {
abstract fun area(): Double
abstract fun perimeter(): Double
fun printDetails() {
println("Area: ${area()}")
println("Perimeter: ${perimeter()}")
}
}
In this example, Shape
is an abstract class with two abstract methods (area()
and perimeter()
) and one concrete method (printDetails()
).
To use an abstract class, you must create a subclass that implements all the abstract methods:
class Circle(private val radius: Double) : Shape() {
override fun area(): Double = Math.PI * radius * radius
override fun perimeter(): Double = 2 * Math.PI * radius
}
In this example, Circle
is a concrete class that extends the abstract Shape
class and provides implementations for the abstract methods.
While abstract classes and interfaces serve similar purposes, they have some key differences:
Abstract Classes | Interfaces |
---|---|
Can have constructors | Cannot have constructors |
Support state (properties with backing fields) | Can only declare abstract properties or properties with default implementations |
A class can extend only one abstract class | A class can implement multiple interfaces |
Abstract classes are a powerful tool in Kotlin for creating flexible and reusable code structures. They provide a balance between code reuse and specialization, making them an essential part of object-oriented design in Kotlin.
For more advanced topics related to abstract classes, explore Kotlin generics and Kotlin sealed classes.