Passing Behavior with Function Objects

A function object is an object used to supply callable behavior through a designated method. You use one when a calculation or processing routine should accept a choice of behavior as a value. In Java, the object is not called with ordinary function-call syntax; the receiving code invokes a method such as apply. The object can also carry settings or remember earlier calls.

Packaging a calculation

Suppose a score-processing routine needs a rule that accepts an integer and returns an integer. The following small interface specifies the method the routine expects:


Java
interface IntRule {
    int apply(int value);
}


A function object can implement that method using a setting stored when the object is constructed:


Java
class OffsetRule implements IntRule {
    private final int offset;

    OffsetRule(int offset) {
        this.offset = offset;
    }

    public int apply(int value) {
        return value + offset;
    }
}


For an object configured with offset bb, its governing calculation is


fb(x)=x+b.f_b(x) = x + b.


The argument supplies the value for this call. The field supplies the setting associated with this object. The constructor chooses the setting; apply performs the calculation. Assume all integer calculations here remain within Java's int range.


Example: new OffsetRule(3) creates an object that adds three points. Calling its apply(8) method returns 11 points. Another object constructed with an offset of five points would supply different behavior through the same method name.



Passing the object and invoking it

A batch routine can receive the rule without knowing its concrete class:


Java
class Batch {
    static int total(int[] values, IntRule rule) {
        int result = 0;
        for (int value : values) {
            result += rule.apply(value);
        }
        return result;
    }
}


For inputs x1,x2,…,xnx_1, x_2, \ldots, x_n, this routine calculates


T=∑i=1nf(xi).T = \sum_{i=1}^{n} f(x_i).


The loop remains unchanged when you supply a different compatible rule object. Its job is to select each input and accumulate the returned values; the supplied object's job is to perform the chosen calculation.


Java
IntRule rule = new OffsetRule(3);
int result = Batch.total(new int[] {4, 9}, rule);


Here, rule supplies an object reference. The expression rule.apply(4) instead invokes the method immediately and produces an integer. To let Batch.total control the calls, pass the object itself.


Processing code calls apply on a function object containing configuration and receives an integer result.



Configuration and changing state

A stateful function object retains mutable information that can affect later calls. For example, an accumulator can add each argument to a stored total and return the updated total. Repeating the same argument can then produce different results.


Stored configuration does not automatically imply changing behavior. The offset in OffsetRule remains fixed after construction, and apply does not modify it.


Object design

Information retained

Consequence for calls

No stored fields used

No object-specific information

Results depend on arguments and any other dependencies

Fixed configuration

Settings chosen at construction

The same argument gives the same result if no other dependencies change

Mutable state

Information updated during use

Later results may depend on earlier calls


When two variables refer to the same object, calls through either variable use that object's fields. Assigning second = first copies a reference; it does not construct an independent object. By contrast, two constructor calls create separate objects with separate instance fields. Remember that state belongs to the object, not to a variable name.

What to remember

  • A function object supplies behavior through a designated method.
  • Passing the object preserves the receiver's choice of when to call it.
  • Fields can store fixed configuration or changing state.
  • Shared references use shared object state; separate instances have separate instance fields.

Example: Handling Fees and Shared Rule Objects

A warehouse uses a function object, an object supplying a calculation through its apply method, to price parcel handling. Each call charges a fixed packing fee plus a fee per item. The object also records how many times apply has been invoked. All monetary values are whole cents, and item counts are nonnegative integers.


Java
interface IntRule {
    int apply(int items);
}

class HandlingCharge implements IntRule {
    private final int packingCents;
    private final int perItemCents;
    private int calls = 0;

    HandlingCharge(int packingCents, int perItemCents) {
        this.packingCents = packingCents;
        this.perItemCents = perItemCents;
    }

    public int apply(int items) {
        calls += 1;
        return packingCents + perItemCents * items;
    }

    public int getCalls() {
        return calls;
    }
}


The parts execute consecutively. Calling getCalls reads the counter without changing it.


a) A new object is created with new HandlingCharge(40, 15). A batch calls apply once for each of three parcels containing 2, 5, and 3 items, then adds the returned charges. Find the batch charge and the object's call count afterward.


The stored configuration sets the packing fee to 40 cents per parcel and the item fee to 15 cents per item. For a parcel containing nn items, the returned charge is


f(n)=40+15ncents.f(n) = 40 + 15n\quad\text{cents}.


The first parcel costs ________, the second costs ________, and the third costs ________. These values follow from the three separate invocations:


f(2)=40+15(2)=70f(5)=40+15(5)=115f(3)=40+15(3)=85.\begin{aligned} f(2) &= 40 + 15(2) = 70 \\ f(5) &= 40 + 15(5) = 115 \\ f(3) &= 40 + 15(3) = 85. \end{aligned}


The batch adds the returned amounts:


T=70+115+85=270 cents.T = 70 + 115 + 85 = 270\ \text{cents}.


Each invocation increments calls once, so its value changes from zero to three. The final results are 270 cents and 3 calls. The counter records invocations; it does not enter the charge formula.


b) The original object is stored in rule. The program now executes the following statements. Find nextCents and the count returned by rule.getCalls() afterward.


Java
HandlingCharge other = rule;
int nextCents = other.apply(4);


The assignment copies the reference, so other and rule refer to the same object. Before this new invocation, that object has recorded ________. No constructor executes during the assignment.


The next parcel's charge uses the original configuration:


nextCents=40+15(4)=100 cents.\text{nextCents} = 40 + 15(4) = 100\ \text{cents}.


The invocation increments the shared object's count from three to four. Reading it through rule observes the update made through other.


The final results are nextCents = 100 cents and 4 calls. Copying a reference does not reset the object's configuration or counter.


c) The program constructs HandlingCharge fresh = new HandlingCharge(40, 15) and calls fresh.apply(1) once. Find this returned charge and the call counts of both fresh and rule afterward.


This constructor call creates a separate object. Its configuration matches the original object's configuration, but its own counter starts at zero.


For one item, the variable portion of the charge is ________. Adding the packing fee gives


f(1)=40+15(1)=55 cents.f(1) = 40 + 15(1) = 55\ \text{cents}.


The invocation increments only fresh's counter, from zero to one. It does not invoke a method on the original object, so rule retains the count of four reached in part b.


The final results are 55 cents, fresh: 1 call, and rule: 4 calls. Matching configuration does not make two separately constructed objects share their instance fields.

A Java score-processing program uses the following interface and variables. BonusRule implements IntRule, and its apply method adds the configured bonus to its argument.


Java
interface IntRule {
    int apply(int value);
}

IntRule rule = new BonusRule(6);
int[] scores = {10, 12};


The method Batch.total(int[] values, IntRule rule) applies its supplied rule to every array element. Which invocation correctly supplies the configured behavior for the batch to invoke?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Java code often passes behaviour to a method instead of passing data alone. Match each term used when writing and passing such behaviour to the description that fits it best.

Match each term
A.

Behaviour handed to other code to be invoked later, for example when a button is clicked

B.

An instance whose fields change between calls, so the same input can produce different outputs

C.

A compact form with parameters, an arrow and a body that creates an instance of a single-abstract-method type

D.

Syntax such as Integer::parseInt that names an existing method to serve as the implementation

E.

An interface type that declares exactly one abstract method, so any implementing instance supplies one operation

F.

An instance whose class exists mainly to package one operation that other code can invoke

Function object

Stateful function object

Lambda expression

Functional interface

Callback

Method reference

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A print shop uses the following Java function object to calculate each job's charge in cents. A batch routine receives one PrintCharge object, calls apply once for each job, and adds the returned charges.


Java
class PrintCharge {
    private final int setupCents = 25;
    private final int perPageCents = 7;

    public int apply(int pages) {
        return setupCents + perPageCents * pages;
    }
}


The batch contains three jobs of 3, 6, and 8 pages. What total does the batch return? Answer in cents, to the nearest whole cent.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice