Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 09 / Stage 2

Object-oriented Kotlin in depth

Goal: Go from Part 7's single plain class to a real class hierarchy — open/override inheritance, interfaces with default methods, abstract classes, data class, sealed class/sealed interface, enum class, object/companion objects, and exactly what == and .equals()/.hashCode() promise each other. Time: ~7 hours · Level: comfortable with Part 7's classes and Part 6's collections

What you will learn

  • Why classes are final by default in Kotlin, and what open class/open fun/override buy you
  • Interfaces: abstract members, default method bodies, implementing more than one at once
  • Abstract classes: constructor state plus unfinished members, and why they can't be instantiated
  • data class: what equals/hashCode/toString/copy/destructuring actually generate, seen by writing the same thing by hand first
  • == vs ===, and the equals/hashCode contract — what breaks when you honor only half of it
  • sealed class/sealed interface: closed hierarchies the compiler can check exhaustively
  • enum class: named instances with their own constructor arguments and methods
  • object declarations (lazy singletons) and companion objects (class-level members, factories)
  • Building a bank account system: an Account hierarchy, an InterestBearing capability, a sealed TransactionResult instead of exceptions, and a companion-object factory

Topics in this part

Practice

Try each one yourself first. Then check the solution.

Every exercise is one file with a top-level fun main(), using only what Parts 1–9 have covered: everything from Stage 1, plus this part's inheritance, interfaces, abstract classes, data classes, equality, sealed types, enums, objects and companion objects.


Exercise 1: Cab fleet fares

Scenario: A ride aggregator computes fare differently per vehicle type, but every vehicle shares a registration number and a driver name. What to do: Write open class Vehicle(val regNumber: String, val driverName: String) with open fun fareInr(km: Double): Double = km * 10.0. Write AutoRickshaw (₹12/km) and Sedan (₹15/km plus a flat ₹20 pickup fee) as subclasses overriding fareInr. Build a List<Vehicle> with one plain Vehicle, one AutoRickshaw and one Sedan, and print each one's regNumber and its fare for an 8 km trip.

Sample output:

MH12-AB-1234 (Suresh Pawar): ₹80.00 for 8 km
MH12-CD-5678 (Ramesh Jadhav): ₹96.00 for 8 km
MH12-EF-9012 (Vikram Singh): ₹140.00 for 8 km

💡 Hint: Sedan's fare is km * 15.0 + 20.0, so an 8 km ride is 8 * 15 + 20 = 140.


Exercise 2: Gig worker payouts

Scenario: A gig platform pays delivery partners by the hour and freelancers a fixed fee, but both should get the same receipt text without writing it twice. What to do: Write interface Payable with an abstract fun payoutInr(): Double and a default method fun receipt(): String = "Payout: ₹%.2f".format(payoutInr()). Write DeliveryPartner(hoursWorked, hourlyRateInr) and Freelancer(fixedFeeInr), each implementing Payable by overriding only payoutInr(). Print receipt() for one of each.

Sample output:

Payout: ₹480.00
Payout: ₹2500.00

💡 Hint: Neither class overrides receipt() — the interface's default body already does the job for both, once payoutInr() is supplied.


Exercise 3: Insurance premiums

Scenario: An insurer prices health and vehicle policies differently, but every policy shares a holder name, a sum insured, and the same summary line. What to do: Write abstract class Policy(val holderName: String, val sumInsuredInr: Double) with abstract fun premiumInr(): Double and a concrete fun summary() = "$holderName: sum insured ₹%.2f, premium ₹%.2f".format(sumInsuredInr, premiumInr()). Write HealthPolicy(holderName, sumInsuredInr, age) with premiumInr() = sumInsuredInr * 0.02 + age * 50.0, and VehiclePolicy(holderName, sumInsuredInr, vehicleAgeYears) with premiumInr() = sumInsuredInr * 0.015 - vehicleAgeYears * 100.0. Print summary() for one of each.

Sample output:

Anjali Nair: sum insured ₹500000.00, premium ₹11700.00
Karan Mehta: sum insured ₹300000.00, premium ₹4200.00

💡 Hint: summary() is written once on Policy and never overridden — only premiumInr() differs per subclass.


Exercise 4: UPI transaction records

Scenario: A UPI app needs to compare two transaction records for equality, and to produce a refunded copy of one without touching the original. What to do: Write data class UpiTransaction(val transactionId: String, val payerVpa: String, val amountInr: Double). Build two separately-constructed transactions with identical field values, print the first one, then print whether they're ==-equal and whether they're the same reference (===). Use .copy(amountInr = 0.0) to build a "refunded" version, print it and the untouched original, then destructure the original into three named vals and print them.

Sample output:

UpiTransaction(transactionId=T2026120100123, payerVpa=neha.joshi@upi, amountInr=1200.0)
Equal: true, same reference: false
After refund copy: UpiTransaction(transactionId=T2026120100123, payerVpa=neha.joshi@upi, amountInr=0.0)
Original unchanged: UpiTransaction(transactionId=T2026120100123, payerVpa=neha.joshi@upi, amountInr=1200.0)
Destructured: id=T2026120100123, vpa=neha.joshi@upi, amount=1200.0

💡 Hint: val (id, vpa, amount) = txnA calls the generated component1()/component2()/component3().


Exercise 5: Fix the broken student ID

Scenario: A college roster class compares student IDs by roll number, but a Set of them isn't catching duplicates the way it should. What to do: Write BrokenStudentId(val rollNumber: String) that overrides only equals() (comparing rollNumber), not hashCode(). Build two instances with the same roll number, print whether they're ==-equal and whether their hashCode()s match, then put the first in a mutableSetOf(...) and print whether the second is recognised as already present. Then write FixedStudentId, identical but also overriding hashCode() to hash rollNumber, and repeat the same three checks on it.

Sample output:

Broken: equals true, same hashCode: false
Broken: Set recognises brokenB as a duplicate: false
Fixed: equals true, same hashCode: true
Fixed: Set recognises fixedB as a duplicate: true

💡 Hint: override fun hashCode(): Int = rollNumber.hashCode() is the whole fix — hash exactly the field equals() compares.


Exercise 6: ATM withdrawal outcomes

Scenario: An ATM's withdrawal attempt can end three different ways, and the bank wants every caller forced to handle all three — no silently-ignored case. What to do: Write sealed class AtmResult with data class Approved(val dispensedInr: Double), data class Declined(val reason: String) and data class CardBlocked(val failedAttempts: Int), all extending it. Write fun describe(result: AtmResult): String using a when with no else branch that handles all three. Build a List<AtmResult> of four attempts (two Approved, one Declined, one CardBlocked), print describe(...) for each, then print how many were Declined (.count { it is AtmResult.Declined }) and the total dispensed amount across every Approved one (.filterIsInstance<AtmResult.Approved>().sumOf { ... }).

Sample output:

Dispensed ₹5000.00
Declined: insufficient balance
Dispensed ₹2000.00
Card blocked after 3 failed attempts
Declined attempts: 1
Total dispensed: ₹7000.00

💡 Hint: Try adding an else -> "unknown" branch, then deleting it again — notice the compiler doesn't complain either way as long as all three is branches are present; the exhaustiveness check is what lets you skip else, not something else is required for.


Exercise 7: Subscription plan limits

Scenario: An app has three subscription tiers, each with a monthly fee and a device limit, and support needs to look one up by the name a user typed. What to do: Write enum class SubscriptionPlan(val monthlyFeeInr: Double, val maxDevices: Int) with entries FREE(0.0, 1), BASIC(199.0, 2), PREMIUM(499.0, 5), and a method perDeviceCostInr() returning monthlyFeeInr / maxDevices (guard maxDevices == 0 to avoid a divide-by-zero, even though no entry here triggers it). Print every entry's name and perDeviceCostInr(). Print SubscriptionPlan.valueOf("BASIC").monthlyFeeInr. Then call SubscriptionPlan.valueOf("ENTERPRISE") inside a try/catch and print the exception type's simple name. Finally print every plan with a monthlyFeeInr above 0.0.

Sample output:

[FREE: ₹0.00/device, BASIC: ₹99.50/device, PREMIUM: ₹99.80/device]
valueOf("BASIC"): 199.0
valueOf("ENTERPRISE") threw IllegalArgumentException
Paid plans: [BASIC, PREMIUM]

💡 Hint: SubscriptionPlan.entries.map { "${it.name}: ₹%.2f/device".format(it.perDeviceCostInr()) } builds the first line in one pass.


Exercise 8: Session registry and invoice factory

Scenario: A support dashboard needs a single shared place to track who's currently logged in, and a billing module needs every invoice to get a unique, sequential number without callers picking it themselves. What to do: Write object SessionRegistry with a private mutableSetOf<String>() of active usernames, and login(username), logout(username), activeCount() functions. Log in "asha.verma", then "ravi.kumar", then "asha.verma" again (a duplicate — a Set drops it silently), print activeCount(), log out "ravi.kumar", and print activeCount() again. Separately, write class Invoice private constructor(val invoiceNumber: String, val amountInr: Double) with a companion object holding a private sequence counter starting at 1000, and a create(amountInr: Double): Invoice factory that increments the counter and builds "INV-$nextSequence". Create two invoices and print both (with a toString() override showing "$invoiceNumber: ₹%.2f".format(amountInr)).

Sample output:

Active sessions: 2
Active sessions after logout: 1
INV-1001: ₹1500.00
INV-1002: ₹2750.00

💡 Hint: Invoice's constructor is private, so the companion object's create(...) is the only way to build one from outside the class — the same pattern Part 9 section 9 used for User.of(...).

Show the solutions for Part 9 (8 files)

solutions/ex01.kt

open class Vehicle(val regNumber: String, val driverName: String) {
    open fun fareInr(km: Double): Double = km * 10.0
}

class AutoRickshaw(regNumber: String, driverName: String) : Vehicle(regNumber, driverName) {
    override fun fareInr(km: Double): Double = km * 12.0
}

class Sedan(regNumber: String, driverName: String) : Vehicle(regNumber, driverName) {
    override fun fareInr(km: Double): Double = km * 15.0 + 20.0
}

fun main() {
    val fleet: List<Vehicle> = listOf(
        Vehicle("MH12-AB-1234", "Suresh Pawar"),
        AutoRickshaw("MH12-CD-5678", "Ramesh Jadhav"),
        Sedan("MH12-EF-9012", "Vikram Singh")
    )
    for (vehicle in fleet) {
        println("${vehicle.regNumber} (${vehicle.driverName}): ₹%.2f for 8 km".format(vehicle.fareInr(8.0)))
    }
}

solutions/ex02.kt

interface Payable {
    fun payoutInr(): Double
    fun receipt(): String = "Payout: ₹%.2f".format(payoutInr())   // default method -- free for every implementer
}

class DeliveryPartner(private val hoursWorked: Double, private val hourlyRateInr: Double) : Payable {
    override fun payoutInr(): Double = hoursWorked * hourlyRateInr
}

class Freelancer(private val fixedFeeInr: Double) : Payable {
    override fun payoutInr(): Double = fixedFeeInr
}

fun main() {
    val payables: List<Payable> = listOf(
        DeliveryPartner(hoursWorked = 6.0, hourlyRateInr = 80.0),
        Freelancer(fixedFeeInr = 2500.0)
    )
    for (payable in payables) {
        println(payable.receipt())
    }
}

solutions/ex03.kt

abstract class Policy(val holderName: String, val sumInsuredInr: Double) {
    abstract fun premiumInr(): Double
    fun summary(): String = "$holderName: sum insured ₹%.2f, premium ₹%.2f".format(sumInsuredInr, premiumInr())
}

class HealthPolicy(holderName: String, sumInsuredInr: Double, private val age: Int) :
    Policy(holderName, sumInsuredInr) {
    override fun premiumInr(): Double = sumInsuredInr * 0.02 + age * 50.0
}

class VehiclePolicy(holderName: String, sumInsuredInr: Double, private val vehicleAgeYears: Int) :
    Policy(holderName, sumInsuredInr) {
    override fun premiumInr(): Double = sumInsuredInr * 0.015 - vehicleAgeYears * 100.0
}

fun main() {
    val policies: List<Policy> = listOf(
        HealthPolicy("Anjali Nair", sumInsuredInr = 500000.0, age = 34),
        VehiclePolicy("Karan Mehta", sumInsuredInr = 300000.0, vehicleAgeYears = 3)
    )
    policies.forEach { println(it.summary()) }
}

solutions/ex04.kt

data class UpiTransaction(val transactionId: String, val payerVpa: String, val amountInr: Double)

fun main() {
    val txnA = UpiTransaction("T2026120100123", "neha.joshi@upi", 1200.0)
    val txnB = UpiTransaction("T2026120100123", "neha.joshi@upi", 1200.0)

    println(txnA)
    println("Equal: ${txnA == txnB}, same reference: ${txnA === txnB}")

    val refunded = txnA.copy(amountInr = 0.0)
    println("After refund copy: $refunded")
    println("Original unchanged: $txnA")

    val (id, vpa, amount) = txnA
    println("Destructured: id=$id, vpa=$vpa, amount=$amount")
}

solutions/ex05.kt

class BrokenStudentId(val rollNumber: String) {
    override fun equals(other: Any?): Boolean = other is BrokenStudentId && rollNumber == other.rollNumber
    // hashCode NOT overridden -- breaks the equals/hashCode contract
}

class FixedStudentId(val rollNumber: String) {
    override fun equals(other: Any?): Boolean = other is FixedStudentId && rollNumber == other.rollNumber
    override fun hashCode(): Int = rollNumber.hashCode()
}

fun main() {
    val brokenA = BrokenStudentId("PU-2201")
    val brokenB = BrokenStudentId("PU-2201")
    println("Broken: equals ${brokenA == brokenB}, same hashCode: ${brokenA.hashCode() == brokenB.hashCode()}")
    val brokenRoster = mutableSetOf(brokenA)
    println("Broken: Set recognises brokenB as a duplicate: ${brokenB in brokenRoster}")

    val fixedA = FixedStudentId("PU-2201")
    val fixedB = FixedStudentId("PU-2201")
    println("Fixed: equals ${fixedA == fixedB}, same hashCode: ${fixedA.hashCode() == fixedB.hashCode()}")
    val fixedRoster = mutableSetOf(fixedA)
    println("Fixed: Set recognises fixedB as a duplicate: ${fixedB in fixedRoster}")
}

solutions/ex06.kt

sealed class AtmResult {
    data class Approved(val dispensedInr: Double) : AtmResult()
    data class Declined(val reason: String) : AtmResult()
    data class CardBlocked(val failedAttempts: Int) : AtmResult()
}

fun describe(result: AtmResult): String = when (result) {
    is AtmResult.Approved -> "Dispensed ₹%.2f".format(result.dispensedInr)
    is AtmResult.Declined -> "Declined: ${result.reason}"
    is AtmResult.CardBlocked -> "Card blocked after ${result.failedAttempts} failed attempts"
}

fun main() {
    val attempts = listOf(
        AtmResult.Approved(5000.0),
        AtmResult.Declined("insufficient balance"),
        AtmResult.Approved(2000.0),
        AtmResult.CardBlocked(failedAttempts = 3)
    )

    attempts.forEach { println(describe(it)) }

    val declinedCount = attempts.count { it is AtmResult.Declined }
    println("Declined attempts: $declinedCount")

    val totalDispensed = attempts.filterIsInstance<AtmResult.Approved>().sumOf { it.dispensedInr }
    println("Total dispensed: ₹%.2f".format(totalDispensed))
}

solutions/ex07.kt

enum class SubscriptionPlan(val monthlyFeeInr: Double, val maxDevices: Int) {
    FREE(0.0, 1),
    BASIC(199.0, 2),
    PREMIUM(499.0, 5);

    fun perDeviceCostInr(): Double = if (maxDevices == 0) 0.0 else monthlyFeeInr / maxDevices
}

fun main() {
    println(SubscriptionPlan.entries.map { "${it.name}: ₹%.2f/device".format(it.perDeviceCostInr()) })

    println("valueOf(\"BASIC\"): ${SubscriptionPlan.valueOf("BASIC").monthlyFeeInr}")

    try {
        SubscriptionPlan.valueOf("ENTERPRISE")
    } catch (e: IllegalArgumentException) {
        println("valueOf(\"ENTERPRISE\") threw ${e::class.simpleName}")
    }

    val paidPlans = SubscriptionPlan.entries.filter { it.monthlyFeeInr > 0.0 }
    println("Paid plans: $paidPlans")
}

solutions/ex08.kt

object SessionRegistry {
    private val activeUsers = mutableSetOf<String>()
    fun login(username: String) {
        activeUsers += username
    }
    fun logout(username: String) {
        activeUsers -= username
    }
    fun activeCount(): Int = activeUsers.size
}

class Invoice private constructor(val invoiceNumber: String, val amountInr: Double) {
    companion object {
        private var nextSequence = 1000
        fun create(amountInr: Double): Invoice {
            nextSequence++
            return Invoice("INV-$nextSequence", amountInr)
        }
    }
    override fun toString(): String = "$invoiceNumber: ₹%.2f".format(amountInr)
}

fun main() {
    SessionRegistry.login("asha.verma")
    SessionRegistry.login("ravi.kumar")
    SessionRegistry.login("asha.verma")   // already logged in -- a Set drops the duplicate
    println("Active sessions: ${SessionRegistry.activeCount()}")
    SessionRegistry.logout("ravi.kumar")
    println("Active sessions after logout: ${SessionRegistry.activeCount()}")

    val invoiceA = Invoice.create(1500.0)
    val invoiceB = Invoice.create(2750.0)
    println(invoiceA)
    println(invoiceB)
}

Common mistakes

Mistake Why it is wrong Fix
Expecting to override any member of any class Classes and members are final by default in Kotlin; overriding one not marked open is a compile error Mark the base member open, and the subclass's override override
Writing Ticket("Nobody", 100) for an abstract class Abstract classes exist only to be extended — they cannot be instantiated directly Instantiate a concrete subclass instead
Overriding equals() without hashCode() Breaks the contract "equal objects must have equal hashes," silently corrupting Set/Map lookups Override both together, hashing exactly the fields equals() compares — or use data class to get both for free
Using == expecting identity (Java habit) In Kotlin, == is structural equality (calls .equals()); === is identity Use === only when "the exact same object" is genuinely the question
Adding an else -> branch to a when over a sealed type "just in case" It silences the exact compile-time check sealed types exist to give — a missed case goes unnoticed Leave it off; handle every subtype by name and let new ones fail to compile until handled
Calling OrderStatus.values() out of habit Allocates a new array on every call Use OrderStatus.entries, the allocation-free modern equivalent
Expecting an object's init block to run at program start object singletons are created lazily, on first access, not eagerly Trust that first access triggers it; print something before and after to see for yourself

Quick recap

  • Classes and their members are final unless marked open; override is required, not optional.
  • An interface can mix abstract members with default-bodied ones, and a class can implement many.
  • An abstract class holds real constructor state but can't be instantiated directly.
  • data class generates equals/hashCode/toString/copy/destructuring from the primary constructor's properties — the exact boilerplate a hand-written class has to get right itself.
  • == is structural equality (.equals()); === is identity. Equal objects must have equal hashes.
  • sealed class/sealed interface give the compiler a complete list of subtypes, so a when over one is exhaustive with no else.
  • enum class is a closed set of instances, each with its own constructor arguments and methods.
  • object is a lazily-created singleton; a companion object attaches members to the class itself and is the idiomatic home for factory functions.

Checklist

  • I can explain why Kotlin classes are final by default and what open/override change.
  • I wrote a class implementing two interfaces at once and used filterIsInstance on it.
  • I wrote an abstract class with both abstract and concrete members.
  • I wrote a class's equals/hashCode/toString by hand, then wrote the same shape as a data class.
  • I broke the equals/hashCode contract on purpose and watched a Set get it wrong, then fixed it.
  • I wrote a sealed hierarchy and an exhaustive when with no else branch.
  • I wrote an enum class with constructor arguments and a method, and used entries/valueOf.
  • I proved an object's init block runs lazily, and wrote a companion-object factory.
  • I built and ran the bank account hierarchy myself, including a rejected withdrawal on each account type.

Search the guide