0
0
Kotlinprogramming~30 mins

Delegation vs inheritance decision in Kotlin - Hands-On Comparison

Choose your learning style9 modes available
Delegation vs Inheritance Decision in Kotlin
📖 Scenario: Imagine you are building a simple app to manage different types of workers in a company. Some workers have special skills, and you want to reuse code efficiently. You will learn when to use inheritance and when to use delegation in Kotlin.
🎯 Goal: You will create classes using inheritance and delegation to share behavior. Then you will decide which approach fits better by comparing outputs.
📋 What You'll Learn
Create a base class with a common function
Create a subclass using inheritance
Create a class using delegation to reuse behavior
Print outputs from both inheritance and delegation examples
💡 Why This Matters
🌍 Real World
In real apps, choosing between inheritance and delegation helps keep code flexible and easier to maintain.
💼 Career
Understanding these concepts is important for Kotlin developers working on clean, reusable code in Android or backend projects.
Progress0 / 4 steps
1
Create a base class with a common function
Create a Kotlin class called Worker with a function work() that returns the string "Working hard".
Kotlin
Need a hint?

Define a class named Worker and inside it a function work() that returns the exact string "Working hard".

2
Create a subclass using inheritance
Create a class called Manager that inherits from Worker. Override the work() function to return "Managing team".
Kotlin
Need a hint?

Use class Manager : Worker() to inherit. Use override fun work() to change the behavior.

3
Create a class using delegation to reuse behavior
Create a class called Assistant that takes a Worker object as a constructor parameter and delegates the work() function to it. Use Kotlin's by keyword for delegation.
Kotlin
Need a hint?

Define class Assistant(private val worker: Worker) : Worker by worker to delegate using the by keyword.

4
Print outputs from inheritance and delegation examples
Create instances of Manager and Assistant (passing a Worker to it). Print the results of calling work() on both instances.
Kotlin
Need a hint?

Create val manager = Manager() and val assistant = Assistant(Worker()). Then print manager.work() and assistant.work().