user710818
user710818

Reputation: 24248

Java call method of descendant class in abstract superclass

I have a big method doComplicateCalculation in abstract class - AbstractClass. 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.

Upvotes: 0

Views: 1449

Answers (3)

Dave
Dave

Reputation: 6179

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;
}

Upvotes: 2

John Kane
John Kane

Reputation: 4443

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

Upvotes: 0

Ralph
Ralph

Reputation: 120761

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

Upvotes: 0

Related Questions