How to share code between some of the subclasses?

shay n :

I have an abstract class with multiple sub-classes (more than 20 as of now) and there is a code and variables that I like to share only between 2 of the Sub-classes.

If I will put the methods and the variables in the Super-class then all of the Sub-classes will have access to them, but I want that only 2 of the Sub-classes will have an access to them and basically will know they exist. Is there a way to achieve this?

Thanks

Marko Previsic :

You can solve it by applying the composition instead of inheritance principle: create a new class that contains the functionality which should be shared between the 2 subclasses and use a reference to an instance of the new class inside of the 2 subclasses.

This way you will avoid having to an additional layer in between the subclasses and the super class and your code will be more flexible and easier to maintain.

This approach is advisable almost always when it doesn't feel natural to add some shared functionality to a super-class and obtain it via inheritance. When in doubt, always ask yourself whether a HAS-A relationship (composition) feels more appropriate than an IS-A relationship (inheritance).

Although grouping together several functionalities in one super-class can be helpful, if you need to share a single functionality between several classes, probably it will be more appropriate to implement it by using composition.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122961&siteId=1