8

There are library classes B and C, both inherit from class A. I have 2 classes that extend B & C, namely MyB & MyC.

    A
   / \    
  B   C 
 /     \
MyB   MyC

MyB & MyC share lots of common code and they are only slightly different.

I want to get rid of duplicate code, how can I do this in java? In C++ it would be possible by creating a common base class and putting everything that is common in it as follows:

    A
   / \  
  B   C 
   \ /
  MyBase
   / \
 MyB MyC
1

4 Answers 4

25

You could use composition:

  • create a new class MyCommon with the common code
  • add an instance of MyCommon in MyB and MyC and delegate the work to MyCommon.
Sign up to request clarification or add additional context in comments.

5 Comments

gah beat me to it. :)
Beat everybody... ;-)
+1, good stuff. this is a helpful article that might be good to include in the answer: javaworld.com/javaworld/jw-10-2005/jw-1024-multiple.html
wow, this is the first time, i have seen +10 reps in less than a minute from answering
This article is what turned on the light bulb for me...
3

Instead of having all your logic in these classes, have all common logic inside class D. Now make it so that MyC and MyB each have a member that is an instance of D. That's called composition.

Comments

1

A class can only extend from one class. However, you can implement multiple interfaces.

Comments

1

In Java you'll use something along the lines of:

  1. Composition (pattern) to encapsulate instances of B and C "in" MyBase.

  2. Refactor B and C (if necessary) to expose a separate interface, say IB and IC

  3. MyBase to implement multiple interfaces: IB and IC, by "doing the right thing" to map methods on interface to internal B and C instances.

  4. MyB and MyC to implement appropriate interface, and map calls to MyBase.

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.