开发者

Java call method of descendant class in abstract superclass

开发者 https://www.devze.com 2023-04-06 15:36 出处:网络
I have a big method doComplicateCalculation in abstract class - Abstract开发者_StackOverflowClass.

I have a big method doComplicateCalculation in abstract class - Abstract开发者_StackOverflowClass. Also have small class Descendant that extends AbstractClass.

I need to introduce in method doComplicateCalculation small changes like:

..............
if (val<0){
   continue;
 }
..................

The problem also more difficulta that big method in internal class of abstract class. How it can be done? Thanks.


This might not be the best answer; but it is the best answer I can give with the information provided. If anything it will get you thinking in the about ways you can address this (because if you're going to be programming for a while, then it won't be the last time you run into problems like this).

In your abstract class, put this:

if (doContinue(val)){
   continue;
}

Then, define the method in your abstract class...

protected boolean doContinue(int val) {
  // Or, put return true if you always want it to do this
  return false;
}

Then, override this method in your concrete class, like this...

protected boolean doContinue(int val) {
  return val < 0;
}


You need to break the big method in pieces, so that you can override the part you need.


That is a difficult question to try to answer generically. One thing that you could do is to try to break up the algorithm in doComplicateCalculation as much as possible. To add the validation maybe make each class extending doComplicateCalculation implement a public boolean validate

You could even do this before or at different times throughout the algorithm. If that isn't possible you could also just override this method (or override some part of the method if you could break it up).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号