25-Comp-B11 Advanced Software Design · Paper printed May 2019
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated
Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
C++ lets a class explicitly grant a named external class (or function) access to its own private members via the friend declaration:
class Contact {
private:
std::string name;
std::string phone;
friend class AddressBookManager; // grants full access to this one class
public:
Contact(std::string n, std::string p) : name(n), phone(p) {}
};
class AddressBookManager {
public:
void mergeDuplicates(Contact& a, Contact& b) {
a.phone = b.phone; // legal: AddressBookManager is a friend
}
};
AddressBookManager can reach Contact's private fields directly because it was explicitly named as a friend; any other class attempting the same access would fail to compile. Java has no equivalent mechanism — the closest substitute is exposing a package-private (default-visibility) accessor and placing both classes in the same package, which is coarser (it opens access to every class in that package, not to one named class).
Advantages of the C++ approach. It allows two tightly-coupled classes to share representation efficiently (no accessor-method call overhead) and precisely (one named friend, not a whole package) when they are conceptually part of the same larger abstraction (e.g. a manager class and the record it manages).
Disadvantages. It breaks encapsulation's information-hiding guarantee for the friend relationship specifically: Contact's representation can no longer change without also checking every declared friend, coupling grows silently as more friends are added, and the friend relationship is not inherited or transitive, which can also surprise maintainers who expect object-oriented access rules to compose the way inheritance does.
Why Java disallows it. Java's design philosophy favours a simpler, more uniform, more strictly enforced encapsulation model: allowing an explicit, arbitrary, one-off access grant like friend was judged to invite exactly the tight, hard-to-track coupling described above, so Java forces all such sharing through the coarser but simpler and safer package-visibility mechanism instead.