问题
I think that there's a solution to my inheritance problem but I can't find it.
I'm developing an Android application (target is Android 2.1) which reuses a SlidingDrawer
(for my menu) on most of the pages. In order to avoid to initialize it on all the Activity I created a DefaultActivity
to do so. It worked well until I had to extends TabActivity
because Java doesn't support multiple inheritance.
Basically I have the following Default activity
public class DefaultActivity extends Activity{
// Declarations
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Some code
}
@Override
protected void onPause() {
// Some code
}
protected void initializeMenu() {
// Init
}
}
Now when I have an activity I do the following
public class SomeActivity extends DefaultActivity{
// Declarations
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
super.initializeMenu();
}
}
But I have a view which extends TabActivity
so I can't do
public class SomeOtherActivity extends TabActivity, DefaultActivity
How can I do to have only one class to extends but which contains the code for an Activity
and TabActivity
?
Thanks.
回答1:
I would use composition instead of inheritance for DefaultActivity.
Create a class ActivityHelper which does everything DefaultActivty does. Then your activities all have a member variable of type ActivityHelper.
public class ActivityHelper {
// Declarations
@Override
public boolean onCreateOptionsMenu(Activity activity, Menu menu) {
// Some code
}
@Override
protected void onPause(activity) {
// Some code
}
protected void initializeMenu(activity) {
// Init
}
}
public class MyActivity extends Activity {
private final ActivityHelper helper;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
helper.onCreateOptionsMenu(this, menu)
}
@Override
protected void onPause() {
helper.onPause(this);
}
protected void initializeMenu() {
helper.initializeMenu(this)
}
}
It's a little more code, but much more flexible. This will only work if your DefaultActivity does not rely on protected methods in Activity.
回答2:
Tab Activity.
This class is deprecated. New applications should use Fragments instead of this class; to continue to run on older devices, you can use the v4 support library which provides a version of the Fragment API that is compatible down to DONUT.
回答3:
Put TabActivity as a data member instead of extending it, and delegate each method you don't want to override to it, and the others implement yourself. That won't solve problems, tough, that the method resides both in DefaultActivity and TabActivity (I guess there are a bunch...). This is why Java does not allow multiple inheritance :)
Hope it helps.
回答4:
usually in general programming we do add a field of that object to use multiple inheritance
来源:https://stackoverflow.com/questions/9081818/bypass-multiple-inheritance-in-java