Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Classes that own objects

โญ beginnerโณ 14 min read๐Ÿ“ Lesson 45 of 256

Composition, private state at design scale, object parameters.

Real AP FRQ 2 (Class Design) gives you a class with a comment spec and a "complete the constructor/methods" task. Two design ideas carry most of it:

Composition โ€” an object holding other objects. A Club has a roster of Strings (or, later, Members):

public class Club {
    private String name;
    private String[] roster;   // an object owns this array
    private int size;          // how many slots are used

    public Club(String clubName, int capacity) {
        name = clubName;
        roster = new String[capacity];
        size = 0;
    }

    public boolean add(String member) {
        if (size >= roster.length) {
            return false;              // full โ€” refuse politely
        }
        roster[size] = member;
        size++;
        return true;
    }
}

Note the division of labor: the array is private, the outside world only calls add/size()/isFull(). That is encapsulation working at design scale โ€” invariants ("size never exceeds capacity") are enforced in one place, the class.

Object parameters: methods take object references. public boolean contains(String member) walks roster[0..size-1] comparing with equals โ€” remember, only the used slots matter, not capacity.