Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multiple inheritance, get rid of duplicate code

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
like image 465
Caner Avatar asked Jul 24 '13 16:07

Caner


4 Answers

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.
like image 130
assylias Avatar answered Oct 21 '22 16:10

assylias


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.

like image 34
Geeky Guy Avatar answered Oct 21 '22 16:10

Geeky Guy


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

like image 43
But I'm Not A Wrapper Class Avatar answered Oct 21 '22 18:10

But I'm Not A Wrapper Class


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.

like image 37
Richard Sitze Avatar answered Oct 21 '22 16:10

Richard Sitze