How to share the same behaviour in different classes

design-patternsinheritance

I have a class called Process, which is extended by some different process types called ProcessA, ProcessB, etc.

class Process{}

class ProcessA extends Process{}
class ProcessB extends Process{}
//...
class ProcessN extends Process{}

There is also another class related to the data of A, but not the Process. I call it TempA

Now ProcessA has a method called calculate(), and TempA needs to be calculated in the same way as ProcessA. As ProcessA extends Process (and Java doesn't allow multiple inheritance), I can't make an abstract class like AbstractA, and use the calculate() method to make these two classes (ProcessA and TempA) have same calculation method.

So how do I make these two classes have the same calculation behaviour/method without copy/paste-duplication of methods?

Best Answer

Favour composition over inheritance. If ProcessA and TempA have common behaviour, abstract that behaviour out into a separate class and have both ProcessA and TempA contain a member of that class. This is also good from a testing point of view, as it means you can separately unit test the common behaviour, and (if necessary) mock it out when testing ProcessA and TempA.