Question 13
Back to Exercise
What is the output of the following Java program?
public class Main {
static class Coffee {
final String size; final int sugar; final boolean milk;
private Coffee(Builder b) { size = b.size; sugar = b.sugar; milk = b.milk; }
@Override public String toString() { return size + "/" + sugar + "/" + (milk ? "milk" : "black"); }
static class Builder {
String size = "M"; int sugar = 1; boolean milk = true;
Builder size(String s) { size = s; return this; }
Builder sugar(int n) { sugar = n; return this; }
Builder black() { milk = false; return this; }
Coffee build() { return new Coffee(this); }
}
}
public static void main(String[] args) {
Coffee.Builder b = new Coffee.Builder().sugar(0);
Coffee first = b.build();
Coffee second = b.size("L").black().build();
System.out.println(first + " " + second);
}
}
- A M/0/milk L/0/black Correct
- B M/1/milk L/0/black
- C L/0/black L/0/black
- D M/0/milk M/0/black
Correct Answer: Option A
Each build() copies the builder's current settings into a new immutable Coffee; changing the builder later does not affect first.
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!