LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 20

An immutable class with "wither" methods Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
final class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    Point withX(int nx) { return new Point(nx, this.y); }
    Point withY(int ny) { return new Point(this.x, ny); }
    @Override public String toString() { return "(" + x + "," + y + ")"; }
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point(1, 2);
        Point q = p.withX(5).withY(9);
        p.withY(100);
        System.out.println(p + " " + q);
    }
}
  • A (1,2) (5,9) Correct
  • B (1,100) (5,9)
  • C (5,9) (5,9)
  • D (1,2) (5,2)
Correct Answer: Option A

Each wither builds a new Point through the constructor; p itself can never change, and the result of p.withY(100) is discarded.

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