Reputation: 249
I have an object oriented design problem. There is a tree of classes built into a library I'm using, so unmodifiable by me. Let's call this A -> B -> C. (Where B inherits from A and C inherits from B).
I'd like to extend A with some additional standalone functionality. This is straightforward, I extend A to A' and add my functionality. However, I'd like B and C to then inherit this additional functionality.
The only way I've been able to do this thus far, is to extend B -> B' and C -> C' and copy-paste the additional functionality into B' and C'. This is obviously far from ideal. Is there a standard design solution to this?
Thanks
Will
N.B. I'm coding in Java if this is relevant.
Upvotes: 1
Views: 69
Reputation: 1016
It looks like you could really use multiple inheritance here, which is obviously not possible in Java.
I don't know what exactly the functionality you want to add is, but you could probably kind of solve this problem by using interfaces. For example you could make A'
an interface, which defines some of the functionality you need, and then have B'
extend B
and implement A'
. This again is far from ideal but it gives the impression of multiple inheritance.
Unfortunately you can't specify method bodies in interfaces, so again you would have to copy-paste.
I'd say write a separate class X
, which contains the additional functionality you need, then have B'
extend B
, C'
extend C
, like you have right now, and simply use class X
inside those classes.
class B' extends B {
private X x;
/* rest of the class */
...
void someMethod() {
...
x.additionalFunctionality();
...
}
...
}
or make the additional functionality static and call it statically.
This way you don't have to copy-paste, simply reuse class X
. However this works if you don't rely on using internal fields of the original classes.
I hope this at least partially helps you. This is quite a challenging problem.
Upvotes: 1