OOPs4Humans

Class Relationships

How objects interact with each other.

Class Relationships

Analogy: concept

Objects don't live in isolation. They interact, own, and depend on each other.

Think of it like Human Relationships:

  • Association: Friends (Independent).
  • Aggregation: Team & Player (Weak Ownership).
  • Composition: Body & Heart (Strong Ownership).
  • Dependency: Driver & Car Key (Temporary Need).

The Relationship Graph

Explore the three main types of relationships.

Class Relationships

Association ("Uses-A")

Two independent objects interacting. No ownership.

Doctor
Treats →
Patient

If the Doctor leaves, the Patient still exists (and vice versa).

1. Association ("Uses-A")

Two independent objects interacting.

  • Example: A Doctor treats a Patient.
  • Lifecycle: If the Doctor leaves, the Patient still exists.

2. Aggregation ("Has-A")

Weak ownership. The child can exist independently of the parent.

  • Example: A Department has Teachers.
  • Lifecycle: If the Department closes, the Teachers can join another department.

3. Composition ("Part-Of")

Strong ownership. The child cannot exist without the parent.

  • Example: A House has Rooms.
  • Lifecycle: If the House is destroyed, the Rooms are destroyed too.

4. Dependency ("Depends-On")

The weakest relationship. One class uses another temporarily, usually as a parameter.

  • Example: A Printer needs a Document to print.
  • Lifecycle: The Printer doesn't own the Document; it just uses it for a moment.

Messaging Between Objects

How do objects talk to each other? Through Methods!

  • Message: The data sent (arguments).
  • Receiver: The object receiving the message.
  • Method: The code that runs in response.
Java Example
Switch language in Navbar
class Person {
    void speak(String message) {
        System.out.println("Says: " + message);
    }
}

Person alice = new Person();
alice.speak("Hello!"); // Sending a message "Hello!" to object 'alice'

The Code

Java Example
Switch language in Navbar
// Composition
class House {
    private Room room;
    House() { room = new Room(); } // Created with House
}

// Aggregation
class Department {
    private List<Teacher> teachers;
    void addTeacher(Teacher t) { teachers.add(t); } // Teacher exists outside
}

// Dependency
class Printer {
    void print(Document doc) {
        System.out.println(doc.getText()); // Uses Document temporarily
    }
}