Delegation and inheritance are ways to share behavior between classes. Choosing the right one helps keep code simple and easy to change.
0
0
Delegation vs inheritance decision in Kotlin
Introduction
When you want to reuse code but keep classes loosely connected.
When you want to change behavior without changing the original class.
When you want to avoid deep or complex class hierarchies.
When you want to add features to a class without modifying it.
When you want to share behavior between unrelated classes.
Syntax
Kotlin
open class Parent { // parent class example } class Child : Parent() { // inheritance example } interface SomeInterface { fun doSomething() } class Delegator(private val delegate: SomeInterface) : SomeInterface by delegate { // delegation example }
Inheritance uses a class extending another class.
Delegation uses a class holding another object and forwarding calls to it.
Examples
Inheritance example: Dog inherits from Animal and changes the sound.
Kotlin
open class Animal { open fun sound() = "Some sound" } class Dog : Animal() { override fun sound() = "Bark" }
Delegation example: SoundDelegator forwards sound() calls to the Cat instance.
Kotlin
interface SoundMaker { fun sound(): String } class Cat : SoundMaker { override fun sound() = "Meow" } class SoundDelegator(private val soundMaker: SoundMaker) : SoundMaker by soundMaker
Sample Program
This program shows inheritance with ColorPrinter extending Printer, and delegation with MultiFunctionDevice forwarding scan() to SimpleScanner and print() to ColorPrinter.
Kotlin
open class Printer { open fun print() = "Printing document" } class ColorPrinter : Printer() { override fun print() = "Printing document in color" } interface Scanner { fun scan(): String } class SimpleScanner : Scanner { override fun scan() = "Scanning document" } class MultiFunctionDevice(private val printer: Printer, private val scanner: Scanner) : Scanner by scanner { fun print() = printer.print() } fun main() { val colorPrinter = ColorPrinter() val simpleScanner = SimpleScanner() val device = MultiFunctionDevice(colorPrinter, simpleScanner) println(device.print()) println(device.scan()) }
OutputSuccess
Important Notes
Use inheritance when classes have a clear "is-a" relationship.
Use delegation to share behavior without tight coupling.
Delegation helps avoid problems with deep inheritance trees.
Summary
Inheritance means one class extends another and inherits its behavior.
Delegation means one class uses another class to do some work.
Choose delegation to keep code flexible and inheritance for clear "is-a" relationships.