I have two classes, let's call them
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:
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
member2, and the relevant function name will be
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
Bar will contain the
Baz class instead of these members. The methods
func() in both
Bar will just call the
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
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