Skip to content
Chethan Yadav_
Object-Oriented Programming

OOP/Lesson 3 of 5/6 min read

Advanced OOP

Composition vs inheritance, association, aggregation and composition, coupling and cohesion, immutability, generics and exception handling in OOP.


On this page

Object relationships

RelationshipMeaningLifetimeUMLExample
Inheritanceis-aN/AHollow triangleCar is a Vehicle
Associationuses / knowsIndependentPlain lineTeacher and Student
Aggregationhas-a (weak)IndependentHollow diamondTeam has Players
Compositionowns (strong)DependentFilled diamondHouse has Rooms
Dependencyuses temporarilyN/ADashed arrowMethod takes a Logger param

Association

A general relationship where objects know about each other but neither owns the other. Can be one-to-one, one-to-many or many-to-many, and uni- or bidirectional. A Doctor treats many Patients; each exists on its own.

Aggregation

A whole-part relationship where parts can exist independently of the whole. Deleting a Department does not delete its Professors; they can move to another department.

class Team {
    private final List<Player> players;
    Team(List<Player> players) { this.players = players; }  // passed in, not created
}

Composition

A strong whole-part relationship: the part's lifetime is bound to the whole. Destroy the House, and its Rooms go with it. The whole usually creates the parts.

class House {
    private final List<Room> rooms = new ArrayList<>();
    House() { rooms.add(new Room("kitchen")); }  // created and owned here
}

Test: can the part exist meaningfully without the whole? Yes means aggregation; no means composition.

Composition over Inheritance

Prefer building behavior by holding objects (has-a) rather than extending classes (is-a).

Problem with inheritance: a Bird base class with fly() breaks for Penguin. Adding FlyingBird, SwimmingBird, FlyingSwimmingBird explodes combinatorially.

interface FlyBehavior { void fly(); }
class CanFly implements FlyBehavior { public void fly() { System.out.println("flap"); } }
class NoFly implements FlyBehavior { public void fly() { } }
 
class Bird {
    private final FlyBehavior flyBehavior;
    Bird(FlyBehavior f) { this.flyBehavior = f; }
    void fly() { flyBehavior.fly(); }
}
InheritanceComposition
BindingCompile timeRuntime (can swap)
CouplingTight (white-box reuse)Loose (black-box reuse)
FlexibilityFixed hierarchyMix and match
Use whenTrue is-a with stable baseSharing or varying behavior

This is the core idea behind the Strategy and Decorator patterns.

Coupling

How much one module depends on the internals of another. Aim for low coupling.

  • Tight coupling: class A does new MySqlDatabase() inside and calls its specific methods. Swapping the DB means rewriting A.
  • Loose coupling: A depends on a Database interface and receives an implementation from outside.

Cohesion

How focused a module's responsibilities are. Aim for high cohesion: a class should do one thing well. A UserService that also formats PDFs and sends SMS has low cohesion.

Low coupling plus high cohesion is the goal; it is what the Single Responsibility and Dependency Inversion principles push toward (SOLID).

Dependency Injection

Instead of a class constructing its dependencies, they are passed in (injected), usually through the constructor.

class OrderService {
    private final PaymentGateway gateway;
    OrderService(PaymentGateway gateway) { this.gateway = gateway; }
}
// production:  new OrderService(new StripeGateway())
// test:        new OrderService(new FakeGateway())

Benefits: testability (inject fakes), loose coupling, configuration in one place. Frameworks like Spring and Angular automate wiring with an IoC container (inversion of control).

Immutable Object

State cannot change after construction. Recipe in Java:

  1. Declare the class final (no subclass can add mutability).
  2. Make all fields private final.
  3. No setters.
  4. Defensive copies of mutable inputs and outputs (lists, dates).
public final class Money {
    private final long cents;
    private final String currency;
    public Money(long cents, String currency) { this.cents = cents; this.currency = currency; }
    public Money plus(Money o) { return new Money(cents + o.cents, currency); }  // returns new object
}

Benefits: thread-safe without locks, safe as hash keys, easy to reason about and cache. Cost: more allocations. Java record types and Kotlin data class with val make this short.

Generics

Write type-safe code that works with many types. The compiler checks types, so no casts and no runtime ClassCastException.

class Box<T> {
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}
Box<String> b = new Box<>();
  • Bounded types: <T extends Comparable<T>> restricts T.
  • Wildcards: List<? extends Number> to read (producer), List<? super Integer> to write (consumer). Mnemonic PECS: producer extends, consumer super.
  • Type erasure (Java): generic types are removed at runtime, so you cannot do new T() or check instanceof List<String>.
  • C++ templates generate a separate copy per type at compile time (no erasure, but code bloat).

Exception Handling

Exceptions separate error handling from normal flow.

try {
    process(file);
} catch (FileNotFoundException e) {
    log.warn("missing file", e);
} finally {
    cleanup();   // always runs
}
Checked (Java)Unchecked
Base classExceptionRuntimeException
Must declare or catchYesNo
Typical causeRecoverable external conditions (I/O)Programming bugs (null, bad index)

Best practices:

  • Catch the most specific exception; never swallow exceptions silently.
  • Use try-with-resources (Java) or with (Python) for cleanup.
  • Throw early (validate inputs), catch late (where you can actually handle it).
  • Create custom exceptions for domain errors (InsufficientFundsException).
  • Overriding methods cannot throw broader checked exceptions than the parent.

Quick revision

  • Association: knows; aggregation: has, independent lifetime; composition: owns, shared lifetime.
  • Prefer composition over inheritance for flexibility and loose coupling.
  • Low coupling, high cohesion.
  • Dependency injection passes dependencies in, making code testable.
  • Immutable: final class, private final fields, no setters, defensive copies.
  • Generics give compile-time type safety; Java erases them at runtime; PECS for wildcards.
  • Checked exceptions for recoverable conditions, unchecked for bugs; never swallow exceptions.