mar*_*bse 17 java methods class abstract
假设我们有一个基类:
public abstract class BaseFragment extends Fragment {
...
protected abstract boolean postExec();
...
}
Run Code Online (Sandbox Code Playgroud)
然后从中派生出其他类(例如Fragment_Movie,Fragment_Weather ......)
public class Fragment_Music extends BaseFragment{
@Override
protected boolean postExec() {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在向基类添加新方法时:
public abstract class BaseFragment extends Fragment {
...
protected abstract boolean postExec();
protected abstract boolean parseFileUrls();
...
}
Run Code Online (Sandbox Code Playgroud)
Eclipse立即显示错误,要求在已派生的类中实现此新方法.
是否在基类中添加"默认"抽象方法,以便即使我们不在派生类中实现它也不显示错误?(因为每次基类附加新方法时都需要花费大量时间来修复每个派生类.)
aka*_*IOT 36
最简单的解决方案是使用存根实现添加方法.将其声明为抽象需要非抽象扩展来实现该方法.
做这样的事情会减轻你的编译问题,虽然在没有覆盖的情况下显然会抛出异常:
public abstract class BaseFragment extends Fragment {
protected boolean doSomethingNew() {
throw new NotImplementedException("method not overridden");
}
}
Run Code Online (Sandbox Code Playgroud)