Methods: Passing and Returning References of an Object FRQ Practice

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

Question 1 of 5

The Basket class stores pears and has put and getPears.

(a) Write a void method load(Basket b) in class Packer that puts 5 pears into b. (b) If bin starts with 2 pears and the caller runs load(bin), state bin.getPears() afterward. (c) Explain why bin changes even though the parameter is a copy.

Question 2 of 5

Complete the table. Then explain why returning the Torch does not create a second object.

public class Torch {
    private int flame;
    public Torch(int n) {
        flame = n;
    }
    public void lower(int n) {
        flame -= n;
    }
    public int getFlame() {
        return flame;
    }
}
public class Stage {
    public Torch same(Torch t) {
        return t;
    }
}
Statement post.getFlame() Do post and extra alias?
Torch post = new Torch(11); 11 extra not created
Torch extra = new Stage().same(post);
extra.lower(4);

Question 3 of 5

A specification says public int readFlame(Torch t) must return the flame and must not modify t.

(a) Write readFlame so it follows the spec. Torch has lower and getFlame. (b) Give one body that would violate the spec. (c) Explain the rule about modifying mutable parameters.

Question 4 of 5

Class Parcel has private int grams.

(a) Write public int heavierThan(Parcel other) in Parcel that returns grams - other.grams using the private field of the parameter. (b) If a is 20 grams and b is 6 grams, state a.heavierThan(b). (c) Explain why Parcel may use other.grams, and why class Rack could not.

Question 5 of 5

A Token stores marks and has stamp and getMarks.

(a) Write public Token markTwice(Token t) in class Rack that calls stamp twice on t and returns t. (b) If chip starts with 4 marks and the caller runs Token also = rack.markTwice(chip); also.stamp(); state both getMarks results. (c) Explain how the parameter alias and the returned reference produce those results.