how to implement Java equivalent of Function Pointers via abstract classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jon williams
    New Member
    • Feb 2011
    • 1

    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:....I'm also trying to figure out how to initialize my concrete classes, there seems to be a problem...
    Code:
          public class Calculator {
    
       public abstract class Functor{
    
        public abstract double Compute(double op1, double op2);
        }
        
        public class Addition extends Functor
        {
           
            public double Compute(double op1, double op2){
                System.out.println("addition= ");return op1 + op2;}
        }
    
        public class Subtraction extends Functor
        {
           
            public double Compute(double op1, double op2){ 
                System.out.println("subtraction= ");return op1 - op2;}
        }
           
        public static void main(String[] args) {
    
            Functor add = new Addition(); // problem here
            Functor minus = new Subtraction();  // problem here
            
    
    	
        }
    }
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    You can not create directly an object of Addition and Subtraction classes.

    Try creating something like this.

    Code:
    Calculator  c_obj = new Calculator ();
    Functor add = null;
    Functor minus = null;
    	    	
    add = c_obj.new Addition();
    minus = c_obj.new Subtraction();
    You can create inner class object by using outer class object.

    Regards
    Dheeraj Joshi
    Last edited by Dheeraj Joshi; Feb 25 '11, 06:41 AM. Reason: Modified initial answer.

    Comment

    Working...