簡體   English   中英

將一個方法傳遞給另一個類中的另一個方法

[英]Passing a method to another method from a different Class

基本上是對微分方程求解器類進行im編碼,該類將從“方程”類中提取方程,並使用rK4方法對其進行求解。

我遇到的主要問題是,我無法找到一種方法,而無需通過繼承來擴展和獲取訪問權,或者在我的ODE類中對該等式方法進行特定的實例化,而不將方法發送給另一個類。

例如,如何使以下代碼正常工作? (請記住,我不允許在ODE類中創建Equation方法的特定實例):

public class Equations {
  public double pressureDrp( double a, double b) {
   return a+b;  //this is just a dummy equation for the sake of the question
  }
  public double waffles( double a, double b) {
   return a-b;  //this is just a dummy equation for the sake of the question
  }

}

public class ODE {
  //x being a method being passed in of "Equations" type.
  public double rK4( Equation method x ) {
    return x(3, 4);   
     //this would return a value of 7 from the pressureDrp method in class Pressure
    //if I had passed in the waffles method instead I would of gotten a value of -1.
  }
}

我將使用一個接口來封裝二進制方法的概念並允許回調 ,例如:

interface BinaryEquation {
   double operate(double d1, double d2);
}

然后可以將其放置在方程式類中,如下所示:

class Equations {
   public static class PressureDrop implements BinaryEquation {

      @Override
      public double operate(double d1, double d2) {
         return d1 + d2;
      }

   }

   public static class Waffles implements BinaryEquation {

      @Override
      public double operate(double d1, double d2) {
         return d1 - d2;
      }

   } 
}

像這樣使用:

class ODE {
   public double rk4(BinaryEquation eq) {
      return eq.operate(3, 4);   
   }
}

或者像這樣更好:

public class BinaryTest {
   public static void main(String[] args) {
      System.out.println("PressureDrop(3, 4): " + new Equations.PressureDrop().operate(3, 4));
      System.out.println("PressureDrop(3, 4): " + new Equations.Waffles().operate(3, 4));
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM