Michael S. Michael S. - 2 months ago 5
Android Question

How not to return a returntype in superclass

I got a question about an abstract class.

I'm developing an android application and wrote an abstract class which extends the AsyncTask<Void, Fragment, Fragment> class. The doInBackground method has already a body in my abstract class but I don't want to return anything here. Now my subclass that extends that abstract class should override that doInBackground method again, call super, do some work and then return a value.

the method in my abstract class looks like this:

@Override
protected Fragment doInBackground(Void... params) {
//do some work without returning a value
}


and the method in my extending subclass looks like this:

@Override
protected Fragment doInBackground(Void.. params) {
super.doInBackground();
MyFragment fragment = new MyFragment();
//do some work with the fragment
return fragment;
}


So if I do not have a return statement in my abstract class Android Studio flags my method with an "Missing return statement" error. Is there a way to avoid this error message, because my subclass has a return value and so it should be no problem, should it?

Answer

Note: This is a general answer, ignoring the specific case shown in the question, which may or may not make sense (see comment).

If the method is supposed to return a value, but the implementation in the superclass can't return a value, then it is not an implementation of that method.

If you still want some common code in the superclass, write that code in a separate method.

abstract class Super {
     public abstract MyObj method();
     protected final void commonLogic() {
         // common logic here
     }
}
class Sub extends Super {
    @Override
    public MyObj method() {
        commonLogic();
        // code here
        return /*something*/;
    }
}

If you want to enforce that the common logic is execute, use the template method pattern.

abstract class Super {
     public final MyObj method() {
         // common logic here
         return afterCommonLogic();
     }
     protected abstract MyObj afterCommonLogic();
}
class Sub extends Super {
    @Override
    protected MyObj afterCommonLogic() {
        // code here
        return /*something*/;
    }
}