Constructors FRQ Practice

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

Question 1 of 5

A crust records bake minutes and whether egg wash was applied.

(a) Write a public class Crust with private int minutes, private boolean eggWash, and a public constructor Crust(int bake, boolean wash) that stores those parameters in the fields. (b) Write a public report method that returns minutes + "/" + eggWash. (c) State the text printed by System.out.print(new Crust(18, true).report());

Question 2 of 5

Label declares no constructor. Complete the default values, then explain why new Label() compiles.

public class Label {
    private int size;
    private double ink;
    private boolean glossy;
    private String text;
    public String dump() {
        return size + "," + ink + "," + glossy + "," + text;
    }
}
Field Type Value after new Label()
size int
ink double
glossy boolean
text String

Question 3 of 5

A tin constructor both initializes state and yields a reference.

public class Tin {
    private int grams;
    public Tin(int start) {
        grams = start;
    }
    public int getGrams() {
        return grams;
    }
}

Tin first = new Tin(200);
Tin second = first;

(a) State the value stored in first.getGrams() immediately after construction. (b) Explain what new Tin(200) returns and what second refers to. (c) If a later statement executed first = new Tin(50);, would second.getGrams() be 50? Explain.

Question 4 of 5

Counter is given and is mutable. A bake log must not alias the caller's Counter.

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 BakeLog with a private Counter minutes field and a public constructor BakeLog(Counter start) that copies start so the field does not alias the original. Copy by constructing a new Counter from start.getValue(). (b) Explain why minutes = start; would be incorrect for a mutable parameter. (c) After BakeLog log = new BakeLog(c); with c holding 9, if the client then calls c.setValue(1), state the value log's Counter still holds.

Question 5 of 5

Peel writes one constructor.

public class Peel {
    private int length;
    public Peel(int cm) {
        length = cm;
    }
    public int getLength() {
        return length;
    }
}

(a) State whether Peel p = new Peel(); compiles, and why. (b) State whether Peel q = new Peel(90); compiles, and the value of q.getLength(). (c) Describe one way to allow both new Peel() and new Peel(90), including the initial length used when no argument is given.