简体   繁体   English

抽象超类中后代类的Java调用方法

[英]Java call method of descendant class in abstract superclass

I have a big method doComplicateCalculation in abstract class - AbstractClass. 我在抽象类中有一个很大的方法doComplicateCalculation - AbstractClass。 Also have small class Descendant that extends AbstractClass. 还有扩展AbstractClass的小类Descendant。

I need to introduce in method doComplicateCalculation small changes like: 我需要在方法doComplicateCalculation中引入一些小变化,如:

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

你需要打破这个大方法,以便你可以覆盖你需要的部分。

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. 您可以做的一件事是尝试尽可能地在doComplicateCalculation中分解算法。 To add the validation maybe make each class extending doComplicateCalculation implement a public boolean validate 要添加验证,可以使每个扩展doComplicateCalculation的类实现一个公共布尔验证

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). 如果那是不可能的,你也可以覆盖这个方法(或者如果你可以将其分解,则覆盖方法的某些部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM