简体   繁体   中英

Passing a method to another method from a different Class

Basically im coding a differential equation solver class that will take equations from an "Equation" Class and solve it using the rK4 method.

The main problem Im running into, is that I can't find a way to send a method to another class without extending and gaining acess through inheritance, or making a specefic instance of that Equation methods in my ODE class.

for example, how would I make the code below work? (remember I am not allowed to make a specific instance of Equation methods within the ODE class):

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

I would use an interface to encapsulate the concept of a binary method and to allow call-backs , something like:

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

This could then be placed in your equations class like so:

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

   } 
}

And used like so:

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

Or better like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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