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
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Caner
  • 57,267
  • 35
  • 174
  • 180
  • Check this out: http://stackoverflow.com/questions/17226364/java-alternative-to-multiple-inheritance – jsedano Jul 24 '13 at 16:10

4 Answers4

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.
Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
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.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
1

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

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.

Richard Sitze
  • 8,262
  • 3
  • 36
  • 48