I have 3 classes A, B, and C. These extend another class D.
Class D has a method that is used in all classes A, B, and C.
Now the problem is that classes A, B, and C should extend different classes and use just the same method from class D.
I can’t believe that I should copy and paste the method in all my classes. Is there something like an include for function in C?
By the way I’m working on an Android app. Class D extends Activity and has a method for managing a common menu of Android activities A, B, and C (this is the official approach as reported in Android’s documentation). However I need that these activities extend different classes such as ActivityList and not just the Activity class.
If your method doesn’t need to access private state, add a static method in class D, and call the static method from A, B, C.
If your method does need to access private state, see if you can factor out the need to use private state by adding a package-private getter to each class, and then use the method in A.
Otherwise, try factoring out some of the logic to a common interface rather than superclass.
Otherwise, try delegating to a helper class. (e.g. composition rather than inheritance as @Marcelo indicated)
Otherwise, repeat the methods in each class A, B, C.
as an example of the common interface approach, combined with a static method in D: