Class Delegation

This Atom is Under Construction

Both composition and inheritance allow you to place subobjects inside your new class (composition explicitly does this—with inheritance it’s implicit).

Use composition when you want the functionality of an existing class inside your new class, but not its interface. When your class needs to reuse an existing implementation and implement an interface, you have two options: inheritance and class delegation.

Class delegation is midway between inheritance and composition, because you place a member object in the class you’re building (like composition), but at the same time your class implements an interface of the member object (like inheritance).

Class delegation makes composition as powerful for reuse as inheritance. In some cases you cannot inherit a class: when the superclass is not open or is final, or your new class is already extending another class. In the latter case you may want to simulate multiple inheritance (multiple inheritance is not supported in Kotlin). Class delegation can help here.

End of sample. See AtomicKotlin.com for full early-access book.



Previous          Next

©2018 Mindview LLC. All Rights Reserved.