mardi 9 mars 2021

Cast Class into another Class / Visitor Pattern

My Program interprets propositional formulas. For Example the Constructor call of

Expression phil1 = new And(new Not(new Variable("a")), new Variable("b"));

shall be outputed as !(a) && b. Everything is working fine except my visitNot method.

When I try to return the not.expr I get the following error:

classes.Not cannot be cast to class classes.Variable (classes.Not and classes.Variable are in unnamed module of loader 'app') 

The testclass for the Printerclass in which the visitNot method is results in:

Expected :!(b && a)
Actual   :!(classes.And@6302bbb1)

I dont know how to return an expression so i have the content.

Below is the Code of all classes.

Not.java

    public class Not implements Expression{

    final Expression expr;

    public Not(Expression expr) {
        this.expr = expr;
    }

    @Override
    public <T> T accept(ExpressionVisitor<T> visitor) {
        return visitor.visitNot(this);
    }
}

Variable.java

public class Variable implements Expression{

    final String name;

    public Variable(String name) {
        this.name = name;
    }

    @Override
    public <T> T accept(ExpressionVisitor<T> visitor) {
        return visitor.visitVariable(this);
    }
}

And.java

public class And implements Expression {

    final Expression lhs;
    final Expression rhs;

    public And(Expression lhs, Expression rhs) {
        this.lhs = lhs;
        this.rhs = rhs;
    }

    @Override
    public <T> T accept(ExpressionVisitor<T> visitor) {
        return visitor.visitAnd(this);
    }
}

Printer.java


public class Printer implements ExpressionVisitor<String> {

    public static String print(Expression expr) {
        return expr.accept(new Printer());
    }


    //And: Operant && Operant
    @Override
    public String visitAnd(And and) {
        //return and.lhs + " && " + and.rhs;
        return visitVariable((Variable) and.lhs) + " && " + visitVariable((Variable) and.rhs);
    }


    @Override
    //TODO
    public String visitNot(Not not) {
        return ("!(" + not.expr + ")");
    }



    //Variable: Name der Variable
    @Override
    public String visitVariable(Variable variable) {
        return variable.name;
    }

}

Expression.java

public interface Expression {

    <T> T accept(ExpressionVisitor<T> visitor);
}

ExpressionVisitor.java

public interface ExpressionVisitor<T> {

    T visitAnd(And and);
    T visitNot(Not not);
    T visitVariable(Variable variable);
}

Aucun commentaire:

Enregistrer un commentaire