// file: Multiplier.java // author: Robert M. Keller // purpose: Example of a Function2 object /** * A Multiplier is a Function2 object that can be used to multiply a * pair of Numbers. If both Numbers are Long or Integer, it returns a * Long. Otherwise it returns a Double. */ class Multiplier implements Function2 { /** * Create a Multiplier with a specific scale factor. * @param _factor the factor to be used */ Multiplier() { } /** * Apply this Multiplier object to two Objects, both of which should be Numbers. * If they are not numbers, a ClassCastException will be thrown. * * @param x the first argument of this function * @param y the second argument of this function * @return a Number containing the product of the arguments. If the arguments * are both Integer or Long, it returns a Long. Otherwise it returns a Double. */ public Object apply(Object x, Object y) { return multiply(x, y); } /** * Multiply two Objects, both of which should be Numbers. * If they are not numbers, a ClassCastException will be thrown. * * @param x the first argument of this function * @param y the second argument of this function * @return a Number containing the product of the arguments. If the arguments * are both Integer or Long, it returns a Long. Otherwise it returns a Double. */ public static Number multiply(Object x, Object y) { if( (x instanceof Long || x instanceof Integer) && (y instanceof Long || y instanceof Integer) ) { long xValue = ((Number)x).longValue(); long yValue = ((Number)y).longValue(); return new Long(xValue*yValue); } else { double xValue = ((Number)x).doubleValue(); double yValue = ((Number)y).doubleValue(); return new Double(xValue*yValue); } } }