# Interface and Extends problem

• April 2nd, 2010, 06:08 AM
DannyGT
Interface and Extends problem
Hi, my problem is more theoretical, I have a program for arithmetic operations and the input could look like this

Node expression = new Plus(new UnaryMinus(new Value(1)), new Multiply(new Value(2), new Value(3)));
// -1 + (2 * 3)

and I could use a little help with designing structure of this... I have Interface for Print of this expression and for calculation, now I would like to use inheritance for those operands ( + , - , / , * ). How to make it most easier? The path I chosen isn't the best I think - I made a class "operator" like this

Code :

```public class operator implements Node {   int a,b,outcome;   public operator(Value a, Value b) { this.a = a.getValue(); this.b = b.getValue(); }   public operator(Value a, plus plusExp) { this.a = a.getValue();   plusExp.calculate();   this.b = plusExp.outcome;   }```

Code :

```public class plus extends operator implements Node { public plus(Value a, Value b) { super(a, b); System.out.println("2x Value of " + a.getValue() + ", " + b.getValue());//just print }   public plus(Value a, plus plusExp) { super(a, plusExp); }   public void calculate() { outcome = a + b; } }```

Code :

```public class Value { private int value;   Value(int i) { this.value = i; }   public int getValue() { return value; }   }   public class unaryMinus extends Value{   public unaryMinus(int a) { super(-a); } }```

Code :

```public interface Node { void calculate(); void printExp();   }```

of course this is only for Plus and for minus, etc. it would be quite long... could you please give me a hint how to make a structure of those operands ( plus, minus,...) and of class Operand ( or is this class even important? ) so I wouldn't have to make all possible combination of operands but only something like this..

(Value a, Value b);
(Value a, Operand b);
(Operand a, Operand b);
(Operand a, Value b);

? :-?

BTW I know that the code isn't complete - I just separated pieces of code so you could take a picture of what I have.
• September 1st, 2011, 01:01 PM
kenster421
Re: Interface and Extends problem
You should consider implementing the Composite/Component Pattern and Visitor Pattern.

The Composite/Component pattern lets you define a hierarchical tree structure that you can use for the operators and the Visitor pattern will allow you to visit each of the locations, letting you visually display the equation.

Composite Pattern - Composite pattern - Wikipedia, the free encyclopedia
Visitor Pattern - Visitor pattern - Wikipedia, the free encyclopedia