An abstract class is a class that is meant to be inherited from, and can’t be created on its own. It can declare abstract members, which every subclass is forced to implement.
Page Contents
Why abstract classes?
In the inheritance lesson, Shape had an area() that returned 0.0, which makes no sense for a “generic shape”. With an abstract class, you can say “every shape has an area, but each kind calculates it differently”:
import kotlin.math.PI
abstract class Shape(val name: String) {
abstract fun area(): Double // no body: subclasses must provide it
fun describe() = "$name with area ${"%.2f".format(area())}"
}
class Circle(val radius: Double) : Shape("Circle") {
override fun area() = PI * radius * radius
}
class Rectangle(val w: Double, val h: Double) : Shape("Rectangle") {
override fun area() = w * h
}
fun main() {
val shapes = listOf(Circle(1.5), Rectangle(2.0, 4.0))
shapes.forEach { println(it.describe()) }
// Shape("Blob") // ❌ can't create an abstract class
}Output:
Circle with area 7.07 Rectangle with area 8.00
If a subclass forgets to implement area(), the code won’t compile.
Abstract classes are open automatically
You don’t need to write open on an abstract class or on its abstract members. Regular (non-abstract) functions in it are still final unless you mark them open.
Abstract properties
abstract class Plan {
abstract val name: String
abstract val monthlyPrice: Int
open val trialDays = 0
fun yearlyPrice() = monthlyPrice * 12
}
class Basic : Plan() {
override val name = "Basic"
override val monthlyPrice = 99
}
class Pro : Plan() {
override val name = "Pro"
override val monthlyPrice = 299
override val trialDays = 14
}
fun main() {
for (p in listOf(Basic(), Pro())) {
println("${p.name}: ₹${p.monthlyPrice}/month, ₹${p.yearlyPrice()}/year, trial ${p.trialDays} days")
}
}Output:
Basic: ₹99/month, ₹1188/year, trial 0 days Pro: ₹299/month, ₹3588/year, trial 14 days
Shared code and state
Unlike an interface, an abstract class can have a constructor and store state:
abstract class PaymentMethod(val label: String) {
private val history = mutableListOf<Int>()
abstract fun fee(amount: Int): Int
fun pay(amount: Int): Int {
val total = amount + fee(amount)
history.add(total)
return total
}
fun totalPaid() = history.sum()
}
class Upi : PaymentMethod("UPI") {
override fun fee(amount: Int) = 0
}
class CreditCard : PaymentMethod("Card") {
override fun fee(amount: Int) = amount * 2 / 100
}
fun main() {
val card = CreditCard()
println(card.pay(1000))
println(card.pay(500))
println("${card.label} total: ${card.totalPaid()}")
println("UPI: ${Upi().pay(1000)}")
}Output:
1020 510 Card total: 1530 UPI: 1000
This is the template method pattern: the abstract class defines the steps (pay), and subclasses fill in the part that differs (fee).
Abstract class vs interface
| Abstract class | Interface | |
|---|---|---|
| Constructor | yes | no |
| Stores state (fields) | yes | no |
| A class can extend… | only one | many |
| Abstract members | yes | yes |
| Members with code | yes | yes |
| Use when | subclasses share code and state | you describe a capability (“can be clicked”, “can be saved”) |
When in doubt, start with an interface. Switch to an abstract class when you need a constructor or shared state.
Abstract class with an interface
A class can extend an abstract class and implement interfaces at the same time:
interface Printable { fun print() }
abstract class Document(val title: String) : Printable
class Invoice(title: String, val total: Int) : Document(title) {
override fun print() = println("$title: ₹$total")
}Common mistakes
- Trying to create an instance:
Shape("x")doesn’t compile for an abstract class. - Giving an abstract function a body: an abstract function has no body. Use
open funif you want a default. - Using an abstract class just to share one function: an extension function or an interface with a default method may be simpler.
Exercise
Create an abstract Employee with an abstract salary() and a shared payslip() function. Implement FullTime (fixed monthly salary) and Contractor (hourly rate × hours).
abstract class Employee(val name: String) {
abstract fun salary(): Int
fun payslip() = "$name: ₹${salary()}"
}
class FullTime(name: String, private val monthly: Int) : Employee(name) {
override fun salary() = monthly
}
class Contractor(name: String, private val rate: Int, private val hours: Int) : Employee(name) {
override fun salary() = rate * hours
}
fun main() {
val staff = listOf(FullTime("Asha", 75000), Contractor("Kabir", 900, 60))
staff.forEach { println(it.payslip()) }
println("Payroll: ₹${staff.sumOf { it.salary() }}")
}Output:
Asha: ₹75000 Kabir: ₹54000 Payroll: ₹129000
FAQ
What is an abstract class in Kotlin?
A class marked abstract that can’t be created directly. It can contain abstract members that subclasses must implement.
Can an abstract class have a constructor in Kotlin?
Yes. Subclasses call it, like class Circle(r: Double) : Shape("Circle").
Should I use an abstract class or an interface?
Use an interface by default. Use an abstract class when subclasses need a shared constructor or stored state.
