Let's say I have the following inheritance tree:
______ Object______
/ \
Food Material
/ \ / \
Egg Carrot Box Axe
Expressed like this in C#
class Object { ... }
class Food : Object { ... }
class OfficeMaterial : Object{ ... }
class Box : OfficeMaterial { ... }
class Spoon : OfficeMaterial { ... }
class Egg : Food { ... }
class Carrot : Food { ... }
And now I want to share the functionality only between the class Box and Egg, for instance:
bool opened = true;
public void Open() { open = true; }
public void Close() { open = false; }
public bool IsOpen() { return opened; }
This is a short example, but it could be something much longer.
What would be the proper way to do it? If I use inheritance, other classes like Carrot and Axe will get it, which is something I do not wish.
UPDATE
Many people mention Composition
. Could someone show me how that would work in the example I presented?