Delegation and inheritance are ways to share behavior between classes. Choosing the right one helps keep code simple and easy to change.
Delegation vs inheritance decision in 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.
open class Animal { open fun sound() = "Some sound" } class Dog : Animal() { override fun sound() = "Bark" }
interface SoundMaker { fun sound(): String } class Cat : SoundMaker { override fun sound() = "Meow" } class SoundDelegator(private val soundMaker: SoundMaker) : SoundMaker by soundMaker
This program shows inheritance with ColorPrinter extending Printer, and delegation with MultiFunctionDevice forwarding scan() to SimpleScanner and print() to ColorPrinter.
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()) }
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.
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.
Practice
Solution
Step 1: Understand inheritance purpose
Inheritance models an "is-a" relationship where a subclass extends a superclass.Step 2: Match the correct use case
Using inheritance is appropriate when a class is a specialized version of another class.Final Answer:
When a class is a specialized type of another class ("is-a" relationship). -> Option CQuick Check:
Inheritance = "is-a" relationship [OK]
- Confusing delegation with inheritance
- Using inheritance for code reuse only
- Thinking inheritance hides implementation
Printer by class Document?Solution
Step 1: Recall Kotlin delegation syntax
Kotlin uses: Interface by instanceto delegate interface implementation.Step 2: Identify correct syntax
class Document(val printer: Printer) : Printer by printer correctly shows delegation withclass Document(val printer: Printer) : Printer by printer.Final Answer:
class Document(val printer: Printer) : Printer by printer -> Option BQuick Check:
Delegation syntax =: Interface by instance[OK]
- Using extends keyword (not Kotlin)
- Writing implements instead of by
- Missing val/var for delegated instance
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) {
println("Console: $message")
}
}
class FileLogger : Logger {
override fun log(message: String) {
println("File: $message")
}
}
class Service(logger: Logger) : Logger by logger
fun main() {
val service = Service(ConsoleLogger())
service.log("Start")
}Solution
Step 1: Understand delegation in Service class
Service delegates Logger interface to the passed logger instance, here ConsoleLogger.Step 2: Trace the log call
Calling service.log("Start") calls ConsoleLogger.log, printing "Console: Start".Final Answer:
Console: Start -> Option AQuick Check:
Delegation calls ConsoleLogger.log = Console: Start [OK]
- Confusing which logger is used
- Expecting FileLogger output
- Thinking delegation copies methods
interface Worker {
fun work()
}
class Employee : Worker {
override fun work() {
println("Employee working")
}
}
class Manager(worker: Worker) : Worker by worker {
fun manage() {
println("Managing team")
}
}
fun main() {
val manager = Manager()
manager.work()
manager.manage()
}Solution
Step 1: Check Manager constructor usage
Manager requires a Worker parameter in constructor but none is provided in main().Step 2: Identify compilation error
Calling Manager() without argument causes a compilation error due to missing parameter.Final Answer:
Manager class missing argument for Worker in constructor call. -> Option AQuick Check:
Constructor argument missing = compilation error [OK]
- Ignoring constructor parameters
- Confusing delegation syntax with inheritance
- Assuming manage() is inaccessible
SmartDevice that can either behave like a Phone or a Camera depending on user choice at runtime. Which approach is best and why?Solution
Step 1: Analyze design needs
SmartDevice needs to switch behavior dynamically between Phone and Camera at runtime.Step 2: Choose delegation for flexibility
Delegation allows SmartDevice to hold and switch between Phone or Camera instances easily without inheritance constraints.Step 3: Exclude other options
Inheritance is static and cannot switch base class at runtime; Kotlin does not support multiple inheritance; static methods do not provide instance behavior.Final Answer:
Use delegation to delegate Phone or Camera behavior to SmartDevice dynamically. -> Option DQuick Check:
Dynamic behavior switching = delegation [OK]
- Trying to use inheritance for runtime behavior switch
- Assuming Kotlin supports multiple inheritance
- Using static methods instead of instance delegation
Ready to prove it?
Pass the test and this pattern moves unknown
