Java how to optional override method in abstract class?

前端 未结 5 1109
小鲜肉
小鲜肉 2021-02-07 01:50

Let\'s say we have a base class:

public abstract class BaseFragment extends Fragment {
    ...
    protected abstract boolean postExec();
    ...
}
相关标签:
5条回答
  • 2021-02-07 02:29

    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");
        }
    }
    
    0 讨论(0)
  • 2021-02-07 02:31

    Abstract methods purpose is to force you to implement them.

    If add an abstract method in your superclass, you have to refactor your code and provide implementation; your program will be inconsistent even with default implementations - what if you need to return a custom type? I'd take my time to provide proper implementation, as I will probably need to call such methods if I added them.

    0 讨论(0)
  • 2021-02-07 02:36

    Only abstract class (including interface) is not expected to declare ALL the methods from its base class.

    So, for instance an interface or abstract class extending one base class or implenting one interface hasn't to declare all the methods. The implementation of the non-implemented method will be the job of the first deeper concrete subclass.

    So for your problem, you eventually could use composition over inheritance adding the collaborator (containing your new common method) as a protected field of your base class.

    Thus, no need to implement nothing in your concrete classes and allowing these ones to use collaborator's method within a proper subclass method.

    You may be interested by the Bridge pattern whose goal is (from wikipedia):

    The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently"

    0 讨论(0)
  • 2021-02-07 02:38

    make your public BaseFragment class abstract

     public abstract class Fragment_Music extends BaseFragment{
                  @Override
    protected boolean postExec() {
        return false;
    } 
    
        }
    
    0 讨论(0)
  • 2021-02-07 02:41

    You could derive a new abstract class with the new abstract method from your base class. Derive concrete classes that should have the new method from this new class and others from the old base class.

    0 讨论(0)
提交回复
热议问题