1

I have a situation in my code where I have 2 classes inheriting from different classes, but still need to have more or less the exact same code. I am looking for a way to make their codes the same without having to copy/paste it each time I modify it.

For more information, I work on Android and I have two activity classes inheriting from either android.app.Activity or android.support.v4.app.FragmentActivity. Those class are exactly the same, but the distinction is needed further down in the code when dealing with fragments. As a result I need exactly the same code on 2 different classes since java does not support multiple inheritance. Is there a way to do that in a less cumbersome ?

EJK
  • 12,332
  • 3
  • 38
  • 55
Laetan
  • 879
  • 9
  • 26
  • 3
    You could use interfaces. You could use delegation instead of inheritance. You could be more specific about what you're trying to do. – khelwood Jan 05 '16 at 14:17
  • "I have a situation in my code where I have 2 classes inheriting from different classes, but still need to have more or less the exact same code. " Strategy pattern comes to mind, but this just sounds like bad design. – Stultuske Jan 05 '16 at 14:21
  • Interface doesn't permit to write more than the signature of function does it? Delegation seems more like what I want. Didn't think of that kind of pattern. – Laetan Jan 05 '16 at 14:23
  • Can't help how Android made their framework. I don't like it either. Each classes have subtil differences in how they handle fragment which mess with my code when I try to use only one of them. – Laetan Jan 05 '16 at 14:24
  • 1
    You could factor out the common code in a class and use aggregation (http://stackoverflow.com/a/269535/2535335) – Johannes Jander Jan 05 '16 at 14:27
  • So delegating all the work to a third class seems to be the best answer. Someone can post that so i can accept it? – Laetan Jan 05 '16 at 14:33

1 Answers1

2

You could use interfaces to extract the commonality of the two classes.

Or you could use delegation instead of inheritance, putting the required functionality in some other class that your other classes call into.

khelwood
  • 55,782
  • 14
  • 81
  • 108