A Java program records how often an adjustment rule is invoked. Every fresh CountingOffset object starts with a stored call count of zero.
interface IntRule { int apply(int value); } class CountingOffset implements IntRule { private int calls = 0; public int apply(int value) { calls += 1; return value + calls; } } class Processor { static int twice(IntRule rule, int value) { return rule.apply(value) + rule.apply(value); } }
Consider each statement independently, starting with fresh objects as specified. Which statements are true? Select all that apply.
Calling apply(10) once on each of two fresh objects returns 11 from each.
Calling Processor.twice with a fresh object leaves its stored call count at zero.
Calling Processor.twice with a fresh object and value 10 returns 23.
Replacing the return expression with 2 * rule.apply(value) preserves the result for a fresh object.
Unlock full course notes by signing up
Shared references to a running total
A warehouse records scanned units using this Java function object. Each invocation adds its argument to the object's stored unit count and returns the updated count.
The following statements execute in the order shown:
Determine middle and last. Give both answers in units as exact integers.
Independent capacity rules
A storage allocator uses function objects to accept or reject requests for whole storage blocks. Each object retains its own remaining capacity. The method returns 1 for an accepted request and 0 for a rejected request.
Two separate objects are constructed:
Execute the calls in table order. Enter each returned integer and the remaining capacity of the object called immediately afterward. All entries are exact integers; capacities are in blocks.
Build and use a pricing rule
A checkout method in a Java shop application should apply whatever discount rule it is given to every price in a cart. Put the following steps for writing and using a named-class function object in the order they must happen, from first to last.
Composing and repeating function objects
The following Java code builds new function objects from existing ones. The method compose returns a function object that first applies g and then applies f to that result, and applyTwice invokes a given function object two times in a row.
Evaluate each of the following expressions and give each answer as an integer: h.apply(4), k.apply(4), applyTwice(h, 2) and applyTwice(k, 1).