How to add same method to multiple classes (activity)
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 activitie开发者_如何学Pythons 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:
interface MyThing
{
public void doMyThing(String subject);
public List<String> getThingNames();
}
class D
{
static void doSomethingComplicatedWithMyThing(MyThing thing)
{
for (String name : thing.getThingNames())
{
boolean useThing = /* complicated logic */
if (useThing)
thing.doMyThing(name);
}
}
}
class A extends SomeClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}
class B extends SomeOtherClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}
class C extends YetAnotherClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}
You should have an instance variable of type D in each of your A, B, and C class definitions and use the method from that instance. That way A, B and C can still extend other classes.
In this case you favor composition over inheritance.
Java does not support multiple inheritance.. A class can only extend only one class. Maybe it is a good idea to use an interface. You can create an interface that contain the method of the D class and make the classes A,B and C to implement this interface.. I don't know if this helps. Here is a link that may be useful for you: http://java.sys-con.com/node/37748
精彩评论