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 ?

6
  • 3
    You could use interfaces. You could use delegation instead of inheritance. You could be more specific about what you're trying to do. Commented Jan 5, 2016 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. Commented Jan 5, 2016 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. Commented Jan 5, 2016 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. Commented Jan 5, 2016 at 14:24
  • 1
    You could factor out the common code in a class and use aggregation (stackoverflow.com/a/269535/2535335) Commented Jan 5, 2016 at 14:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.