Force cancel a non-abstract method

I have a String foo() method in an abstract class that already performs a few preliminary calculations, but cannot deliver the final result that the method should return. Therefore, I want every non-abstract class inherited from my abstract class to implement foo in a way that is called first by super() , and then the result is computed. Is there any way to force this in java?

+5
source share
3 answers

Yes, reworked to use a template template and incorporating an abstract method:

 public abstract class AbstractSuper { public final String foo() { // Maybe do something before calling bar... String initialResult = bar(); // Do something common, eg validation return initialResult; } protected abstract String bar(); } 

Basically, if you want to force subclasses to override a method, it should be abstract, but it should not be a method called by other code ...

+15
source

There is no way to do this in Java. However, you can declare another method that is abstract and call it. Like this:

 public final String foo() { String intermediate = ... // calculate intermediate result; return calculateFinalResult(intermediate); } protected abstract String calculateFinalResult(String intermediate); 

This way you will be forced to override calculateFinalResult . No call to the super instance required. Also, subclasses will not be able to override your foo() , as it is declared as final .

+4
source

Something like that?

 public abstract class MyBean { public final String foo(){ String preFinalResult = [...]; return doFinalResult(preFinalResult) } protected abstract String doFinalResult(String preFinal); } 
+3
source

All Articles