Java alternative for empty overridden method in sub class

3k views Asked by At

I have the following class hierarchy:

BaseActivity:

public abstract class BaseActivity extends AppCompatActivity {
   protected abstract void bindView();
}

ASubActivity:

public class ASubActivity extends BaseActivity {
  @Override
  protected void bindView() {
    //No implementation
  }
}

BSubActivity:

public class BSubActivity extends BaseActivity {

  private Toolbar toolbar;

  @Override
  protected void bindView() {
     toolbar = (Toolbar) findViewById(R.id.toolbar);
  }

  ...
}

I find this to be a bit ugly. I would rather just not have the bindView() method in the ASubActivity. Is there a best practice way to do this?

NOTE: the BaseActity does contain some other abstract methods that are used by both subclasses.

3

There are 3 answers

0
Yash Sampat On BEST ANSWER

One way would be to put bindView() in an interface instead of BaseActivity and have only BSubActivity implement that interface:

public interface BindViewInterface{
    protected void bindView();
}

Then there would be no need to have bindView() BSubActivity.

Another way would be to not make bindView() an abstract method:

public abstract class BaseActivity extends AppCompatActivity {
    protected void bindView() {}
}
0
Christopher On

Depending on your use case you could make your bindView()-method not abstract:

public abstract class BaseActivity extends AppCompatActivity {
    protected void bindView() {
    }
}

In this case you do not have to override the method in your ASubActivity. But you can override the method in your BSubActivity.

0
Philip Couling On

This is a more general java problem than being specific to android. All abstract methods MUST be implemented which makes the code messy.

The only other alternative is to implement the // do nothing version in the parent class (BaseActivity in your case). You don't have to make it abstract just because it does nothing in an abstract class.

public abstract class BaseActivity extends AppCompatActivity {
   protected void bindView() {}
}

ASubActivity:

public class ASubActivity extends BaseActivity {
   // Nothing to see here.
}