Dron Bhattacharya
02/24/2023, 3:02 AMinterface IMoving {
fun move()
}
class Walking : IMoving {
override fun move() {
println("Walking")
}
}
class Animal(private val movable: IMoving) : IMoving {
override fun move() {
movable.move()
}
}
fun main() {
var movable = Walking()
var animal = Animal(movable)
animal.move()
}
Here we are still extending IMoving
with Animal
even though we are saying we don't want to do subclassing like this. In this way, we are also not able to limit the usage of methods when requiredChris Lee
02/24/2023, 3:07 AMTODO("Not implemented")
. This is ok in a limited set of scenarios; biggest drawback is lack of compile-time type safety (exceptions not uncovered until runtime)
2. Create a separate type that implements just the operations required. This can delegate (entirely, or in part) to other implementations.Dron Bhattacharya
02/24/2023, 3:12 AMimplementation
is not equivalent to inheritance
??Chris Lee
02/24/2023, 3:14 AMDron Bhattacharya
02/24/2023, 3:15 AMChris Lee
02/24/2023, 3:17 AMby
delegation, yes, you are saying “I implement this interface, with calls forwarded to this delegate”. You an do delegation in other ways as well (it’s a general pattern of delegating certain operations to other parties). If your interface is too big consider splitting it up into focused responsibilities; classes can then implement one or more of those interfaces as appropriate.Dron Bhattacharya
02/24/2023, 3:19 AMChris Lee
02/24/2023, 3:20 AMDron Bhattacharya
02/24/2023, 3:23 AMby
for delegating classes only when I want to delegate all methods.
If I want to limit/restrict some methods, by
is not useful. In a case like this, I should do delegation as I said for classes A and B.Chris Lee
02/24/2023, 3:25 AMby
delegation requires implementing an entire interface, which by default has all methods forwarded to a delegate - you can selectively override methods. If you are wish to expose a different interface you can do as above for classes A and B.Dron Bhattacharya
02/24/2023, 3:26 AM