Java如何在抽象类中可选覆盖方法?

Java如何在抽象类中可选覆盖方法?

问题描述:

假设我们有一个基类:

public abstract class BaseFragment extends Fragment {
    ...
    protected abstract boolean postExec();
    ...
}

然后从中派生出其他类(例如 Fragment_Movie、Fragment_Weather ...)

And then derive from it to have other class(es) (e.g. Fragment_Movie, Fragment_Weather ...)

public class Fragment_Music extends BaseFragment{
    @Override
    protected boolean postExec() {
        return false;
    } 
}

但是,当向基类添加新方法时:

However, when adding a new method to the base class:

public abstract class BaseFragment extends Fragment {
    ...
    protected abstract boolean postExec();
    protected abstract boolean parseFileUrls();
    ...
}

Eclipse 立即显示错误,要求在已经派生的类中实现这个新方法.

Eclipse instantly shows up error asking to implement this new method in the already derived classes.

是否可以在基类中添加一个默认"抽象方法,以便即使我们不在派生类中实现它也不会显示错误?(因为每次基类追加新方法时,修复每个派生类都会花费大量时间.)

Is there away to add a "default" abstract method in the base class, so that it does not show error even if we don't implement it in the derived class? (because it'd take lot of time to fix each derived class every time the base class appends new method. )

最简单的解决方案是添加带有存根实现的方法.将其声明为抽象需要非抽象扩展来实现该方法.

The easiest solution would be to add the method with a stubbed implementation. Declaring it abstract requires non-abstract extensions to implement the method.

做这样的事情会缓解你的编译问题,虽然它在不覆盖的情况下使用时显然会抛出异常:

Doing something like this would ease your compilation problems, though it will obviously throw exceptions when used without overriding:

public abstract class BaseFragment extends Fragment {
    protected boolean doSomethingNew() {
        throw new NotImplementedException("method not overridden");
    }
}