This exercise focusses on two topics:
- inheritance, and
- representing logical expressions as Java data types.
You should have encountered propositional logic in the Logic
and Computation course last semester. In this exercise, you will take
initial steps in represent formulas of propositional logic in Java. We
will restrict our attention to expressions such as
PropVar p = new PropVar("P");
Here is an implementation of the class PropVar:
public class PropVar { private String propVar; public PropVar(String str) { this.propVar = str; } public String toString() { return propVar; } }
The method toString() simply returns the string we used in initialization.
Let’s return to the Wffs
We will want to control the syntactic aspects of BinaryWffs, by listing the allowed operators. To do this, we will use Java’s enum type. This is is a type whose instance variable consist of a fixed set of constants. We will take these to be AND, OR and IF. Each of the variables can be defined to have its own toString() method.
public enum Operator { AND { public String toString() { return "&"; } }, OR { public String toString() { return "|"; } }, IF { public String toString() { return "->"; } } }
You can look at the Oracle Java Tutorial to find out more about enum types. Note that client code will be able to use the values in the enum type as Operator.AND and so on.
Here is an example of client code to construct instances of AndWff:
PropVar p = new PropVar("P"); PropVar q = new PropVar("Q"); AndWff andWff = new AndWff(p, q); System.out.println(andWff); // (P & Q)
Create an class BinaryWff which meets the following API:
- public BinaryWff(PropVar left, PropVar right)
- public void setOp(Operator op)
- public Operator getOp()
- public PropVar getLeft()
- public PropVar getRight()
- public String toString()
- Return a string of the form (<left> <op> <right>).
Note
Ideally you would declare your class to be abstract, since it will not have any direct instances. However, do not do this now, since it also makes it impossible to directly test your class.
An automated test has been created for this exercise: BinaryWffTest.java.
Next, create a class AndWff which is a subclass of BinaryWff. The only thing that you need to specify is the constructor:
- public AndWff(PropVar left, PropVar right)
- Class constructor. This should call the constructor of its superclass, and also specify that its operator is Operator.AND.
An automated test has been created for this exercise: AndWffTest.java.
The definition for IfWff would be exactly the same, except that the operator would be specified as Operator.IF. However, you can skip this.
An automated test has been created for this exercise: IfWffTest.java.