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 Lamp class from this topic stores watts and has dim and getWatts.

(a) Write a void method shade(Lamp bulb) in class Booth that dims bulb by 8. (b) If desk is a Lamp with 40 watts and the caller runs shade(desk), state desk.getWatts() afterward. (c) Explain why desk changes even though Java copies arguments.

Question 2 of 5

Complete the table. Then explain why returning a reference does not copy the Cart object.

public class Cart {
    private int items;
    public Cart(int n) {
        items = n;
    }
    public void add(int n) {
        items += n;
    }
    public int getItems() {
        return items;
    }
}
public class Clerk {
    public Cart same(Cart c) {
        return c;
    }
}
Statement red.getItems() Do red and also alias?
Cart red = new Cart(2); 2 also not created
Cart also = new Clerk().same(red);
also.add(5);

Question 3 of 5

A specification says public int countItems(Cart c) must return the number of items in c and must not modify c.

(a) Write countItems so it follows the spec. Cart has getItems and add. (b) Give one example of a body that would violate the spec. (c) Explain why a method should not modify a mutable parameter unless the spec requires it.

Question 4 of 5

Class Cart has private int items and a constructor that stores a starting count.

(a) Write public int extraOn(Cart other) in Cart that returns this object's items plus other.items using the private field of the parameter. (b) Explain why that private access is legal. (c) Explain why a method in a different class named Clerk could not use other.items even if other is a Cart parameter.

Question 5 of 5

A Bowl stores scoops and has add and getScoops.

(a) Write public Bowl bigger(Bowl b) in class Shelf that adds 3 scoops to b and returns b. (b) If cup starts with 1 scoop and the caller runs Bowl also = shelf.bigger(cup); also.add(1); state cup.getScoops() and also.getScoops(). (c) Explain both the mutation through the parameter and the effect of returning that reference.