0Pricing
Kotlin Academy · Lesson

Delegation vs Inheritance

Choose composition.

Two Ways to Reuse

Inheritance and delegation both reuse behavior. Inheritance says a class is a kind of another. Delegation says a class has a collaborator it forwards to.

The classic advice: prefer composition over inheritance.

Inheritance Example

With inheritance, a subclass extends a base and overrides members. The base must be open in Kotlin.

open class Animal {
    open fun sound() = "..."
}

class Dog : Animal() {
    override fun sound() = "woof"
}

fun main() {
    println(Dog().sound())
}

All lessons in this course

  1. The by Keyword
  2. Delegating to Members
  3. Delegation vs Inheritance
  4. Practical Patterns
← Back to Kotlin Academy