Type up the arithmetic expressions interface and classes that were presented during the lectures. (You can copy and paste the code from the slides if you like, but you will probably learn more by typing it out by hand, thinking again about what is happening.)
Let us define the depth of an arithmetic expression as follows:
- A literal expression has depth 0
- An add expression's depth is one plus the maximum depth of its left and right operands
- A multiply expression's depth is defined similarly
- A factorial expression's depth is one plus the depth of its operand
Add a new method signature:
public int depth();
to the Expr
interface.
The Java compiler will now complain that the classes which implement
Expr
(LiteralExpr
, AddExpr
,
MulExpr
, FactExpr
), do not implement
depth
. Do you understand why the compiler makes this
complaint?
Add a depth
implementation to each of the classes that
implements Expr
. Write a main
method in which
to experiment with your implementations.