When to Choose Delegation over Inheritance?
We'll cover the following
How to choose
Both delegation and inheritance are useful, but you have to decide when one is a better choice than the other. Inheritance is common, highly used, and is a first-class feature in OO languages. Though delegation is more flexible, there’s no special support for it in many OO languages. We often shy away from delegation since it takes more effort to implement than inheritance. Kotlin supports both inheritance and delegation, so we can freely choose between them based on the problem at hand. The following rules will serve you well in deciding which one to choose:
-
Use inheritance if you want an object of a class to be used in place of an object of another class.
-
Use delegation if you want an object of a class to simply make use of an object of another class.
Differences explained with an example
You can see the two design choices in the following figure—a Candidate
class using inheritance on the left and delegation on the right.
Get hands-on with 1400+ tech skills courses.