Constructors FRQ Practice

Responses receive AI feedback against a rubric after submission. Scores are practice estimates.

Question 1 of 5

A winch stores cable length in meters.

(a) Write a public class Winch with a private int meters and a public constructor Winch(int start) that stores start in meters. (b) Write public getMeters that returns meters. (c) State the value printed by System.out.print(new Winch(14).getMeters()); and explain that new Winch(14) both sets state and yields a reference.

Question 2 of 5

FogHorn declares no constructor. Fill the defaults and explain why new FogHorn() is legal.

public class FogHorn {
    private int blasts;
    private double pitch;
    private boolean armed;
    private String code;
    public String dump() {
        return blasts + "," + pitch + "," + armed + "," + code;
    }
}
Field Type Value after new FogHorn()
blasts int
pitch double
armed boolean
code String

Question 3 of 5

Slip's constructor copies parameters into the wrong fields.

public class Slip {
    private int length;
    private int beam;
    public Slip(int len, int width) {
        length = width;
        beam = len;
    }
    public String sizes() {
        return length + "x" + beam;
    }
}

(a) For Slip s = new Slip(30, 12); state the values of length and beam after construction. (b) Rewrite the constructor body so length stores len and beam stores width. (c) Explain why constructor parameters exist in this class.

Question 4 of 5

Counter is given and is mutable. A harbor stay must keep its own copy of the night count.

public class Counter {
    private int value;
    public Counter(int start) {
        value = start;
    }
    public void setValue(int n) {
        value = n;
    }
    public int getValue() {
        return value;
    }
}

(a) Write a public class HarborStay with a private Counter nights field and a public constructor HarborStay(Counter start) that copies start with new Counter(start.getValue()). (b) Explain what goes wrong if the constructor uses nights = start; instead. (c) After HarborStay stay = new HarborStay(c); with c holding 4, if the client calls c.setValue(9), state the value still stored in stay's Counter.

Question 5 of 5

Lamp currently has only Lamp(int). A client also needs new Lamp() to mean 0 lumens.

public class Lamp {
    private int lumens;
    public Lamp(int n) {
        lumens = n;
    }
    public int getLumens() {
        return lumens;
    }
}

(a) State whether Lamp a = new Lamp(); compiles with the class as written, and why. (b) Write an additional public constructor that sets lumens to 0. (c) After both constructors exist, state lumens for new Lamp() and for new Lamp(40).