Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to optional override method in abstract class?

Tags:

Let's say we have a base class:

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

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

like image 519
markbse Avatar asked Sep 27 '12 11:09

markbse


1 Answers

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");     } } 
like image 134
akaIDIOT Avatar answered Oct 06 '22 15:10

akaIDIOT