What features exist in inheritance and delegation in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, inheritance is closed (final) by default, and classes and methods need to be explicitly marked as open to allow inheritance and overriding. Inheritance is supported only from one class, but multiple interfaces can be implemented.
When inheriting, the constructor of the base class is called after the constructor of the derived class:
open class Base(val name: String) {
init { println("Initializing Base") }
open fun greeting() { println("Hello from Base") }
}
class Derived(name: String, val age: Int) : Base(name) {
init { println("Initializing Derived") }
override fun greeting() { println("Hello from Derived") }
}
Delegation in Kotlin is implemented at the language level using the by keyword. It allows passing the implementation of an interface to another object. This is a convenient alternative to inheritance of implementation (which is not directly supported).
interface Greeter {
fun greet(name: String)
}
class GreeterImpl : Greeter {
override fun greet(name: String) {
println("Hello, $name!")
}
}
class DelegateGreeter(greeter: Greeter) : Greeter by greeter
Here, DelegateGreeter delegates the call of the greet method to the greeter object.
Comparison:
| Feature | Inheritance | Delegation (by) |
|---|---|---|
| Relationship | "is a" (inherits) | "has a" (contains) |
| Implementation | Direct class extension | Passing implementation to an object |
| Multiplicity | One base class | Multiple interfaces |
| Flexibility | Less flexible | More flexible, composition |
| Visibility | Inherits protected and public | Works through interfaces |
Delegation is often preferred over inheritance for achieving flexibility and avoiding the problems of "fragile base class".