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.

  1. 1.

    Create an instance with new TenPercentOff() and store it in a variable of type PriceRule.

  2. 2.

    Call checkout(prices, rule), passing the stored instance as the second argument.

  3. 3.

    Write a class TenPercentOff that implements PriceRule and overrides apply to return 0.9 * price.

  4. 4.

    Declare an interface PriceRule with one abstract method double apply(double price).

  5. 5.

    Inside checkout, call rule.apply(p) for each price p and add up the returned values.

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

More Function Objects Questions: