Constructors

AP Computer Science A· difficulty 3/5

public class Rect {
    private int w, h;
    public Rect() { this(1, 1); }
    public Rect(int side) { this(side, side); }
    public Rect(int w, int h) {
        this.w = w;
        this.h = h;
    }
    public int area() { return w * h; }
}
// ...
Rect r = new Rect(5);
System.out.println(r.area());

What is printed?

  • A

    1

  • B

    5

  • C

    25

    check_circle
  • D

    10

Explanation

Rect(5) calls this(5,5) which sets w=5 and h=5, so area returns 25.

Want 10 more like this — adaptive to your weak spots?

Related questions