Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement Java equivalent of Function Pointers via abstract classes

Im trying to to create a simple 4 function calculator using a jump table without switch case or if/else statements. I understand I can create the jump table via function pointers but I am kindda blanking out. I've started with the addition and subtraction part of the program but am trying to grasp the design/strategy to use. I am also getting an error when putting the method in the array, so far this is what i have:

public class Calculator {

          public abstract class Functor{

            abstract double Compute(double op1, double op2);
            }

     class Addition extends Functor
    {

        public double Compute(double op1, double op2){ return op1 + op2;}
    }

    class Subtraction extends Functor
    {

        public double Compute(double op1, double op2){ return op1 - op2;}
    }



    public static void main(String[] args) {

        Functor add = new Addition();     // Problem here
        Functor sub = new Subtraction();  // and here



    }
}

any help or ideas for the step in the right direction is greatly appreciated! thanks in advance!

like image 749
Java Beans Avatar asked Feb 05 '26 08:02

Java Beans


1 Answers

Let's try this instead:

public enum Operation {
  PLUS("+") {
    double apply(double x, double y) { return x + y; }
  },
  MINUS("-") {
    double apply(double x, double y) { return x - y; }
  },
  TIMES("*") {
    double apply(double x, double y) { return x * y; }
  },
  DIVIDE("/") {
    double apply(double x, double y) { return x / y; }
  };
  private final String symbol;

  Operation(String symbol) {
    this.symbol = symbol; 
  }

  @Override public String toString() {
    return symbol; 
  }
  abstract double apply(double x, double y);
}

This will only work if you're using Java 5 or later, which has generics and enums. What this does is it gives you a static set of operations. You access them by typing Operation.PLUS or Operation.MINUS, etc.

To test it try this:

public static void main(String[] args) {
  double x = Double.parseDouble(args[0]);
  double y = Double.parseDouble(args[1]);

  for (Operation op : Operation.values())
    System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}

For more information consult Effective Java, Second Edition by Joshua Bloch.

It's worth pointing out that Java has no notion of "function pointers". Rather you simple write an interface and write a class that implements that interface. The correct class to use is selected at runtime; hence, that is a "jump table" but it's hidden behind the semantics of object-oriented programming. This is known as polymorphism.

like image 72
Edawg Avatar answered Feb 08 '26 00:02

Edawg