Bird
Raised Fist0
Kotlinprogramming~10 mins

Delegation vs inheritance decision in Kotlin - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Delegation vs inheritance decision
Start
↓
Need to reuse behavior?
↓
Is "is-a" relationship clear?
↓
Use Inheritance
↓
Use Delegation
↓
No reuse needed
↓
End
Decide reuse by checking if a clear "is-a" relationship exists; if yes, use inheritance, else use delegation.
Execution Sample
Kotlin
interface Printer {
    fun print()
}

class ConsolePrinter : Printer {
    override fun print() = println("Printing to console")
}

class Report(private val printer: Printer) {
    fun generate() {
        // Delegation
        printer.print()
    }
}
This code shows delegation: Report class uses a Printer interface implementation to print, instead of inheriting.
Execution Table
StepActionEvaluationResult
1Check if reuse of behavior is neededYesProceed to next step
2Check if "is-a" relationship is clearNoChoose delegation
3Create interface PrinterInterface definedPrinter interface ready
4Implement ConsolePrinter classClass implements PrinterConsolePrinter ready
5Create Report class with Printer propertyReport delegates printingDelegation setup complete
6Call Report.generate()Calls printer.print()Prints "Printing to console"
7EndAll steps doneExecution complete
💡 Decision made to use delegation because "is-a" relationship was not clear
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5After Step 6Final
printernullInterface definedInstance of ConsolePrinterAssigned to ReportUsed in generate()Print output done
reportnullnullnullCreated with printergenerate() calledDelegation works
Key Moments - 2 Insights
Why do we choose delegation when the "is-a" relationship is unclear?
Because inheritance implies a strong "is-a" relationship. If that is not clear, delegation allows reuse without forcing that relationship, as shown in execution_table step 2.
Can delegation still reuse behavior like inheritance?
Yes, delegation reuses behavior by calling methods on another object, as seen in execution_table step 6 where Report calls printer.print().
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the decision made to use delegation?
AStep 5
BStep 4
CStep 2
DStep 6
💡 Hint
Check the 'Evaluation' column where the choice between inheritance and delegation is decided.
According to variable_tracker, what is the state of 'printer' after Step 4?
AInstance of ConsolePrinter
Bnull
CInterface defined
DAssigned to Report
💡 Hint
Look at the 'printer' row and the column 'After Step 4' in variable_tracker.
If the "is-a" relationship was clear, which step would change in the execution_table?
AStep 6 would not call printer.print()
BStep 2 would choose inheritance instead of delegation
CStep 3 would be skipped
DStep 5 would create a different class
💡 Hint
Focus on the decision step about relationship clarity in execution_table step 2.
Concept Snapshot
Delegation vs Inheritance Decision:
- Use inheritance if there is a clear "is-a" relationship.
- Use delegation to reuse behavior without "is-a".
- Delegation involves calling methods on another object.
- Inheritance involves extending a class.
- Delegation offers more flexibility and less tight coupling.
Full Transcript
This visual execution shows how to decide between delegation and inheritance in Kotlin. First, check if you need to reuse behavior. If yes, check if the "is-a" relationship is clear. If it is, use inheritance. If not, use delegation. The example code defines a Printer interface and a ConsolePrinter class. The Report class delegates printing to a Printer instance instead of inheriting. The execution table traces each step, showing the decision and how delegation works. The variable tracker shows how the printer variable changes from interface definition to instance and usage. Key moments clarify why delegation is chosen without a clear "is-a" relationship and how delegation still reuses behavior. The quiz tests understanding of decision points and variable states. The snapshot summarizes the key rules for choosing delegation or inheritance.

Practice

(1/5)
1. Which statement best describes when to use inheritance in Kotlin?
easy
A. When you want to hide implementation details completely.
B. When you want to reuse code without creating a parent-child relationship.
C. When a class is a specialized type of another class ("is-a" relationship).
D. When you want to avoid any relationship between classes.

Solution

  1. Step 1: Understand inheritance purpose

    Inheritance models an "is-a" relationship where a subclass extends a superclass.
  2. Step 2: Match the correct use case

    Using inheritance is appropriate when a class is a specialized version of another class.
  3. Final Answer:

    When a class is a specialized type of another class ("is-a" relationship). -> Option C
  4. Quick Check:

    Inheritance = "is-a" relationship [OK]
Hint: Use inheritance for clear "is-a" relationships [OK]
Common Mistakes:
  • Confusing delegation with inheritance
  • Using inheritance for code reuse only
  • Thinking inheritance hides implementation
2. Which Kotlin syntax correctly shows delegation of interface Printer by class Document?
easy
A. class Document : Printer(printer)
B. class Document(val printer: Printer) : Printer by printer
C. class Document : Printer implements printer
D. class Document(printer: Printer) extends Printer

Solution

  1. Step 1: Recall Kotlin delegation syntax

    Kotlin uses : Interface by instance to delegate interface implementation.
  2. Step 2: Identify correct syntax

    class Document(val printer: Printer) : Printer by printer correctly shows delegation with class Document(val printer: Printer) : Printer by printer.
  3. Final Answer:

    class Document(val printer: Printer) : Printer by printer -> Option B
  4. Quick Check:

    Delegation syntax = : Interface by instance [OK]
Hint: Delegation uses ': Interface by instance' syntax [OK]
Common Mistakes:
  • Using extends keyword (not Kotlin)
  • Writing implements instead of by
  • Missing val/var for delegated instance
3. What is the output of this Kotlin code?
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")
}
medium
A. Console: Start
B. File: Start
C. Start
D. Compilation error

Solution

  1. Step 1: Understand delegation in Service class

    Service delegates Logger interface to the passed logger instance, here ConsoleLogger.
  2. Step 2: Trace the log call

    Calling service.log("Start") calls ConsoleLogger.log, printing "Console: Start".
  3. Final Answer:

    Console: Start -> Option A
  4. Quick Check:

    Delegation calls ConsoleLogger.log = Console: Start [OK]
Hint: Delegation calls passed instance methods [OK]
Common Mistakes:
  • Confusing which logger is used
  • Expecting FileLogger output
  • Thinking delegation copies methods
4. Identify the error in this Kotlin code using delegation:
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()
}
medium
A. Manager class missing argument for Worker in constructor call.
B. Employee class does not implement work() method.
C. Delegation syntax is incorrect; should use extends instead of by.
D. manage() method cannot be called on Manager instance.

Solution

  1. Step 1: Check Manager constructor usage

    Manager requires a Worker parameter in constructor but none is provided in main().
  2. Step 2: Identify compilation error

    Calling Manager() without argument causes a compilation error due to missing parameter.
  3. Final Answer:

    Manager class missing argument for Worker in constructor call. -> Option A
  4. Quick Check:

    Constructor argument missing = compilation error [OK]
Hint: Check constructor parameters when using delegation [OK]
Common Mistakes:
  • Ignoring constructor parameters
  • Confusing delegation syntax with inheritance
  • Assuming manage() is inaccessible
5. You want to design a Kotlin class SmartDevice that can either behave like a Phone or a Camera depending on user choice at runtime. Which approach is best and why?
hard
A. Use static methods in SmartDevice to mimic Phone and Camera features.
B. Use inheritance with SmartDevice extending Phone or Camera based on a flag.
C. Use multiple inheritance to inherit both Phone and Camera directly.
D. Use delegation to delegate Phone or Camera behavior to SmartDevice dynamically.

Solution

  1. Step 1: Analyze design needs

    SmartDevice needs to switch behavior dynamically between Phone and Camera at runtime.
  2. Step 2: Choose delegation for flexibility

    Delegation allows SmartDevice to hold and switch between Phone or Camera instances easily without inheritance constraints.
  3. 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.
  4. Final Answer:

    Use delegation to delegate Phone or Camera behavior to SmartDevice dynamically. -> Option D
  5. Quick Check:

    Dynamic behavior switching = delegation [OK]
Hint: Use delegation for flexible runtime behavior changes [OK]
Common Mistakes:
  • Trying to use inheritance for runtime behavior switch
  • Assuming Kotlin supports multiple inheritance
  • Using static methods instead of instance delegation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard