Bypass multiple inheritance in Java

一世执手 提交于 2019-12-06 08:22:32

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.

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.

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.

usually in general programming we do add a field of that object to use multiple inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!