Composition instead of inheritance c# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Composition instead of inheritance c#

I have a class Monster { move() attack() } we can create: melee monster : monster overr attack() ranged monster : monster ovverr attack() flying monster : monster overr move() swimming monster : monster overr move() how to create FlyingRangeMonster and MeleeSwimmingMonster without duplicating code? I suppose we should abandon inheritance and use composition. How to realízate it in this case ? Thank you!

12th Mar 2021, 6:49 AM
Tatarochka_
Tatarochka_ - avatar
2 Answers
+ 3
How about an interface monster with methods move and attack
12th Mar 2021, 6:56 AM
Oma Falk
Oma Falk - avatar
0
but if we create an interface we will duplicate code (e.g. melee monster and swimmingmeleemonster will have same realization of attack method)
12th Mar 2021, 8:57 AM
Tatarochka_
Tatarochka_ - avatar