I have two classes in Java which basically act the same but one represents a multiplier and the other represents a divider. I want to create a parent class which both of them can extend but I don't know how to do that. What should I pass to the parent class? this are both of the classes I have created:
import java.util.HashMap;
public class Divide extends Operator {
private String DIVIDE = " / ";
public Divide(Expression leftExp, Expression rightExp){
super(leftExp,rightExp);
}
/*
* We assume that our divider is not zero. If it is, then we can handle it with exceptions*
*/
@Override
public float calculate(HashMap<String,Integer> map) {
return this.leftExp.calculate(map) / this.rightExp.calculate(map);
}
private String isWithParentheses(Expression exp) {
return exp.getClass().getSimpleName() == "Variable" ||
exp.getClass().getSimpleName() == "Number" ?
exp.toString() : "(" + exp.toString() + ")";
}
@Override
public String toString() {
String leftExpString = this.isWithParentheses(this.leftExp);
String rightExpString = this.isWithParentheses(this.rightExp);
return leftExpString + DIVIDE + rightExpString;
}
@Override
public void print() {
System.out.println(this.toString());
}
}
import java.util.HashMap;
public class Multiply extends Operator {
private String MULTIPLY = " * ";
public Multiply(Expression leftExp, Expression rightExp){
super(leftExp,rightExp);
}
@Override
public float calculate(HashMap<String,Integer> map) {
return this.leftExp.calculate(map) * this.rightExp.calculate(map);
}
private String isWithParentheses(Expression exp) {
return exp.getClass().getSimpleName() == "Variable" ||
exp.getClass().getSimpleName() == "Number" ?
exp.toString() : "(" + exp.toString() + ")";
}
@Override
public String toString() {
String leftExpString = this.isWithParentheses(this.leftExp);
String rightExpString = this.isWithParentheses(this.rightExp);
return leftExpString + MULTIPLY + rightExpString;
}
@Override
public void print() {
System.out.println(this.toString());
}
}
Aucun commentaire:
Enregistrer un commentaire