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
- The by Keyword
- Delegating to Members
- Delegation vs Inheritance
- Practical Patterns