Inheritance, Interfaces and Sealed Classes

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

Classes Are Final by Default

open class Animal(val name: String) {
    open fun speak() = "..."
}
class Dog : Animal("Dog") {
    override fun speak() = "Woof"
}

Mark extensibility explicitly with open - safer APIs by default.

Interfaces with Defaults

interface Payable {
    fun pay(amount: Int): Boolean
    fun receipt() = "Paid - thank you"  // default body allowed
}

Sealed Classes: Closed Hierarchies

sealed interface Result {
    data class Ok(val orderId: String) : Result
    data class Fail(val reason: String) : Result
}
fun message(r: Result) = when (r) {
    is Result.Ok -> "Order ${r.orderId}"
    is Result.Fail -> "Failed: ${r.reason}"
}  // exhaustive - no else needed

Abstract and Enum Classes

  • abstract - shared base with unfinished parts.
  • enum with properties - enum class Level(val points: Int) { BRONZE(10), SILVER(50) }.

Sealed class tree with exhaustive when

Key Points

  • Final-by-default plus open equals deliberate design.
  • Sealed hierarchies make when exhaustive and safe.
  • Model API results as sealed types, not nullable strings.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in