/** * Represents the constant polynomial type. * @author Dung X. Nguyen */ class ConstPoly extends APolynomial { /** * @param coef the constant coefficient for this ConstPoly. */ public ConstPoly(double coef) { _coef = coef; } public int getDegree() { return 0; } /** * Throws NoSuchElementException. */ public APolynomial getLowerPoly() { throw new java.util.NoSuchElementException ("Constant polynomial has no lower order term!"); } /** * If parameter p is a constant polynomial then return a ConstPoly whose coefficient * is the sum of the coefficients of this ConstPoly and p. * Otherwise asks p to add this APolynomial to itself. */ public APolynomial add(APolynomial p) { return 0 == p.getDegree()? new ConstPoly (_coef + p.getLeadCoef()): p.add (this); /* Software Engineering Issue: The previous line of code can be replaced by * new NonConstPoly (p.getLeadCoef(), p.getDegree(), p.getLowerPoly().add (this)); * Perhaps this is more efficient, but it introduces a loose coupling between * ConstPoly and NonConstPoly: ConstPoly must know how to call the constructor * for NonConstPoly. */ } /** * Returns the coefficient of this ConstPoly. */ public double eval(double x) { return _coef; } /** * Returns the String representation of the coefficient of this ConstPoly. */ public String toString () { return Double.toString(_coef); } /** * Called by an APolynomial that contains this ConstPoly as its lower order polynomial. * Returns the empty String if this ConstPoly is the zero polynomial, otherwise * returns " + " followed by the String representation of this ConstPoly's coefficient. */ String toString4LowerPoly () { return (0 == _coef)? "": " + " + Double.toString(_coef); } }