Part 09 / Topic 4 of 10
Abstract classes: partial implementation, not just a contract
An abstract class sits between a plain class and an interface: like a class, it can hold constructor parameters and real state; like an interface, it can leave members unimplemented — and like neither, it can never be instantiated directly.
abstract class Ticket(val passengerName: String, val distanceKm: Int) {
abstract fun fareInr(): Double
abstract val travelClass: String
// A concrete member, shared by every subclass as-is.
fun printTicket() {
println("$passengerName | $travelClass | $distanceKm km | ₹%.2f".format(fareInr()))
}
}
class SleeperTicket(passengerName: String, distanceKm: Int) : Ticket(passengerName, distanceKm) {
override val travelClass = "Sleeper"
override fun fareInr() = 0.45 * distanceKm + 20.0
}
--- IRCTC fare chart for the same 560 km route ---
Rohan Gupta | Sleeper | 560 km | ₹272.00
Sneha Iyer | AC 3-Tier | 560 km | ₹676.00
Imran Sheikh | AC First Class | 560 km | ₹1690.00
Total fare if one passenger booked all three: ₹2638.00
printTicket() is written once, on the abstract class, and every subclass gets it unchanged —
only the parts that genuinely differ (fareInr(), travelClass) are abstract. Writing
Ticket("Nobody", 100) anywhere would fail to compile: Ticket exists only to be extended.
🔍 Going deeper: choose interface vs abstract class by what you're modeling. "Can send a notification" (a capability, possibly shared by otherwise-unrelated classes) is an interface. "Is a kind of ticket, sharing a passenger name, a distance and a print routine" (a common shape with real state) is an abstract class. A class can implement many interfaces but extend only one (abstract or not) class.
Full program: examples/03_abstract_classes.kt.
Done here? The practice set for Part 9 — including the solutions — is on the part page.