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
                You could use composition:
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.
A class can only extend from one class. However, you can implement multiple interfaces.
In Java you'll use something along the lines of:
Composition (pattern) to encapsulate instances of B and C "in" MyBase.
Refactor B and C (if necessary) to expose a separate interface, say IB and IC
MyBase to implement multiple interfaces: IB and IC, by "doing the right thing" to map methods on interface to internal B and C instances.
MyB and MyC to implement appropriate interface, and map calls to MyBase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With