I have two classes, let's call them Foo
and Bar
. They both extend different classes (Foo extends X
, Bar extends Y
), which have some common ancestor "way up" the inheritance tree, something like this:
Both Foo
and Bar
have some common class members (and some more members which they don't share), and I would like to implement a method which will be the same for both classes, acting on these members. The catch is - I cannot change the inheritance tree and add a superclass which will be the same for both (while this might be a sign for a bad design of the classes and inheritance, this is not what I ask here).
For simplicity, let's assume that the similar class members will be member1
and member2
, and the relevant function name will be func()
.
One option I thought of, is to encapsulate the similar class members in a new class, and create the relevant method for it.
For example, I can create a class named Baz
which will hold both member1
and member2
, and Foo
and Bar
will contain the Baz
class instead of these members. The methods func()
in both Foo
and Bar
will just call the baz.func()
.
This is one indeed solution. However, what should be a solution where I can't change the class members as well? In that case, I thought of making both Foo
and Bar
implement an interface (for simplicity, let's call it IFunc
). And create a method (either static
or not) somewhere else which will have an IFunc
argument which will mimic func
. But this seems like a not so good solution. What will be a better solution for this case?
To clarify: I am trying to eliminate code duplication in the implementation of func
Thanks!
func
). I will clarify it in the question