Question 6
Back to Exercise
What is the output of the following Java program?
class Rectangle {
private double width, height;
Rectangle(double w, double h) { width = w; height = h; }
public void setWidth(double w) { if (w > 0) width = w; }
public double getArea() { return width * height; } // no area field to keep in sync
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(2, 5);
double a1 = r.getArea();
r.setWidth(4);
r.setWidth(-1);
System.out.println(a1 + " " + r.getArea());
}
}
- A 10.0 20.0 Correct
- B 10.0 10.0
- C 10.0 -5.0
- D 20.0 20.0
Correct Answer: Option A
Because area is calculated from the current fields, it can never be stale.
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!