LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 9

Method chaining by returning this Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following Java program?

Main.java
class Order {
    private final StringBuilder items = new StringBuilder();
    private double total;

    Order add(String item, double price) {
        if (!items.isEmpty()) items.append(", ");
        items.append(item);
        total += price;
        return this;                  // returning the same object allows chaining
    }

    @Override public String toString() { return "[" + items + "] Rs " + total; }
}

public class Main {
    public static void main(String[] args) {
        Order o = new Order().add("Pen", 20).add("Book", 120).add("Bag", 899.5);
        System.out.println(o);
    }
}
  • A [Pen, Book, Bag] Rs 1039.5 Correct
  • B [Bag] Rs 899.5
  • C [Pen] Rs 20.0
  • D Compilation error
Correct Answer: Option A

Each add returns this, so the next call works on the same Order (a fluent interface).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links