Skip to content Skip to sidebar Skip to footer

Bypass Multiple Inheritance In Java

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 me

Solution 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.

publicclassActivityHelper { 
  // Declarations@OverridepublicbooleanonCreateOptionsMenu(Activity activity, Menu menu) {
    // Some code
  }

  @OverrideprotectedvoidonPause(activity) {
    // Some code
   }

   protectedvoidinitializeMenu(activity) {
    // Init


   }
}

publicclassMyActivityextendsActivity { 
  private final ActivityHelper helper;

  @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    helper.onCreateOptionsMenu(this, menu)
  }

  @OverrideprotectedvoidonPause() {
    helper.onPause(this);
  }

   protectedvoidinitializeMenu() {
     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.

Solution 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.

Solution 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.

Solution 4:

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

Post a Comment for "Bypass Multiple Inheritance In Java"