SyntaxPilot
Courses/CS Fundamentals for Placements/Lesson 14

CS Fundamentals for Placements · Lesson 14 of 90 · 15 min

OOP 3: abstraction, relationships and design principles

abstraction vs encapsulationassociationaggregationcompositionis-a vs has-acomposition over inheritancecoupling and cohesionSOLID (SRP, OCP, LSP, ISP, DIP)shallow vs deep copyimmutable objectsexception handlingchecked vs unchecked exceptionsgenerics/templatesfriend function/class

These are the notes for CS Fundamentals for Placements, episode 14, the last of three episodes on object-oriented programming (OOP). Episodes 12 and 13 gave you the tools: classes, objects, encapsulation, inheritance and polymorphism. This episode is about using them well. You invent: is-a vs has-a, association, aggregation and composition, composition over inheritance, abstraction vs encapsulation, coupling and cohesion, the five SOLID principles (SRP, OCP, LSP, ISP, DIP), shallow vs deep copy, immutable objects, exception handling with checked vs unchecked exceptions, generics and C++ templates, the C++ friend function/class, garbage collection basics, and four design patterns (singleton, factory, observer, strategy). Every term is explained in plain words the first time it appears, and there is a full glossary at the end. All outputs and error messages below are real: Java programs were compiled and run with javac/java 21, C++ programs with g++ 13.3, on 29 October 2026.

Refresher: a class is a blueprint and an object is one thing made from it; encapsulation bundles data with the methods that guard it and hides the data (private); inheritance (extends) lets a child class reuse a parent's code (an is-a relationship); an interface is a list of methods a class promises to have; polymorphism means one call behaves differently depending on the real object. A reference is a variable that holds an object's address, not the object itself.

The seven problems

Problem What it teaches
Inheritance that leaks is-a vs has-a, association, aggregation, composition, composition over inheritance, abstraction vs encapsulation
Classes welded together Coupling, cohesion, dependency injection, SOLID: SRP, OCP, LSP, ISP, DIP
A copy that isn't a copy Shallow vs deep copy, immutable objects
Programs that crash Exceptions, try/catch/finally, throw/throws, checked vs unchecked, Error
Wrong types sneak in Generics, type parameters, C++ templates
Trusted outsiders and cleanup C++ friend function and friend class, garbage collection
Problems everyone has Design patterns: singleton, factory, observer, strategy

Problem 1: inheritance that leaks (has-a and composition)

A stack is a pile where you add on top (push) and take from the top (pop): last in, first out (LIFO), like a pile of plates. Java ships a Stack class. Watch what it allows:

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<String> plates = new Stack<>();  // last in, first out
        plates.push("plate 1");
        plates.push("plate 2");
        plates.push("plate 3");
        plates.add(0, "sneaky");  // at the BOTTOM?!
        plates.remove(1);         // from the middle?!
        System.out.println(plates);
        System.out.println(Stack.class.getSuperclass());
    }
}

Output:

[sneaky, plate 2, plate 3]
class java.util.Vector

It inserted at the bottom and removed from the middle, which no stack should allow. The last line shows why: java.util.Stack's parent class is java.util.Vector, a growable list. Because Stack extends a list, it inherited every list method, including the ones that break the stack's one rule. (The Stack documentation itself says the Deque interface "should be used in preference to this class", for example Deque<Integer> stack = new ArrayDeque<Integer>();, per the Java SE 8 API docs for Stack.)

The honest is-a test fails: a stack is not a kind of list; a stack uses a list to store its items. That's a has-a relationship: one object holds another as a field.

Three ways objects relate

Relationship Meaning Real-life example Lifetime
Association two objects know and use each other a teacher teaches students both live independently
Aggregation (weak has-a) a whole holds parts that can exist without it a department has teachers close the department, teachers remain
Composition (strong has-a) a whole owns parts that can't exist without it a house has rooms demolish the house, rooms are gone

In code, aggregation usually means the part is created outside and passed in (new Department(existingTeachers)); composition means the whole creates and owns its parts (private ArrayList<String> list = new ArrayList<>() inside PlateStack). In UML diagrams aggregation is drawn with a hollow diamond and composition with a filled one.

The fix: composition

import java.util.ArrayList;

class PlateStack {
    private ArrayList<String> list = new ArrayList<>();  // has-a
    void push(String p) { list.add(p); }
    String pop() { return list.remove(list.size() - 1); }
    public String toString() { return list.toString(); }
}

public class Main {
    public static void main(String[] args) {
        PlateStack plates = new PlateStack();
        plates.push("plate 1");
        plates.push("plate 2");
        plates.push("plate 3");
        System.out.println(plates.pop() + " " + plates);
        plates.add(0, "sneaky");
    }
}

Output:

Main.java:17: error: cannot find symbol
        plates.add(0, "sneaky");
              ^
  symbol:   method add(int,String)
  location: variable plates of type PlateStack
1 error

The leak is now a compile error: PlateStack simply has no add method. Remove that line:

plate 3 [plate 1, plate 2]

Composition over inheritance: when you only want to use another class's abilities, hold it as a private field and expose only what you need. Inherit only for a true is-a where the child keeps every promise of the parent (see LSP below). Composition also lets you swap the inner object later without changing users of your class.

Abstraction vs encapsulation

PlateStack showed only what a stack does (push, pop) and hid how (an ArrayList).

Abstraction Encapsulation
Idea show only the essential operations, hide the complexity bundle data with its methods and hide the data
Level design: what to show implementation: how to hide it
Car example steering wheel and pedals, not fuel-injection timing the locked bonnet
Java tools interfaces, abstract classes private fields, getters/setters

Problem 2: classes welded together (coupling, cohesion, SOLID)

class SmsSender {
    void send(String msg) { System.out.println("SMS: " + msg); }
}

class OrderService {
    SmsSender sms = new SmsSender();     // welded to SMS
    void placeOrder() {
        sms.send("order placed");
    }
}

public class Main {
    public static void main(String[] args) {
        new OrderService().placeOrder();
        // now the client wants email instead...
    }
}

Output:

SMS: order placed

It works, but OrderService creates its own SmsSender with new. To switch to email, WhatsApp or both, you must edit OrderService itself and retest order logic that never changed.

  • Coupling is how strongly one class depends on another class's details. Here coupling is tight: change SmsSender and OrderService must change.
  • Cohesion is how focused one class is on one job. A class that places orders, sends SMS, prints invoices and writes logs has low cohesion.
  • Good design aims for low coupling and high cohesion.

The fix: depend on an interface, and have it handed in

interface Notifier {                    // the abstraction
    void send(String msg);
}
class SmsSender implements Notifier {
    public void send(String m) { System.out.println("SMS: " + m); }
}
class EmailSender implements Notifier {
    public void send(String m) { System.out.println("Email: " + m); }
}

class OrderService {
    private final Notifier notifier;
    OrderService(Notifier n) { notifier = n; }   // handed in
    void placeOrder() { notifier.send("order placed"); }
}

public class Main {
    public static void main(String[] args) {
        new OrderService(new SmsSender()).placeOrder();
        new OrderService(new EmailSender()).placeOrder();
    }
}

Output:

SMS: order placed
Email: order placed

OrderService didn't change by a character. Giving an object its helpers (its dependencies) from outside, through the constructor or a setter, instead of creating them inside, is dependency injection.

SOLID: five principles for classes that survive change

Letter Principle In one line Our example
S Single Responsibility (SRP) a class should have one job, one reason to change OrderService handles orders; sending messages belongs to Notifiers
O Open/Closed (OCP) open for extension, closed for modification add WhatsAppSender as a new class; edit nothing old
L Liskov Substitution (LSP) a child must work anywhere its parent works, with no surprises Square breaks Rectangle code (below)
I Interface Segregation (ISP) many small interfaces beat one big one; never force unused methods split Machine into Printer, Scanner, Fax
D Dependency Inversion (DIP) high-level code depends on abstractions, not concrete classes OrderService depends on Notifier, not SmsSender

L: the Liskov substitution principle

Maths says a square is a rectangle, so Square extends Rectangle seems right:

class Rectangle {
    int w, h;
    void setWidth(int w)  { this.w = w; }
    void setHeight(int h) { this.h = h; }
    int area() { return w * h; }
}

class Square extends Rectangle {          // a square is-a rectangle?
    void setWidth(int w)  { this.w = w; this.h = w; }
    void setHeight(int h) { this.w = h; this.h = h; }
}

public class Main {
    static void resize(Rectangle r) {
        r.setWidth(5);
        r.setHeight(4);
        System.out.println("expected 20, got " + r.area());
    }
    public static void main(String[] args) {
        resize(new Rectangle());
        resize(new Square());
    }
}

Output:

expected 20, got 20
expected 20, got 16

resize was written for rectangles and is correct for them; a Square silently gives 16. Liskov's rule (named after computer scientist Barbara Liskov): objects of a child class must be usable wherever the parent is expected without breaking the program's correctness. If not, the is-a is false for your code. Fix: don't make Square a child of Rectangle; let both implement a common Shape interface with area().

I: interface segregation

interface Machine { void print(); void scan(); void fax(); }   // too big

class BasicPrinter implements Machine {
    public void print() { System.out.println("printing"); }
    public void scan()  { throw new UnsupportedOperationException(); }  // forced
    public void fax()   { throw new UnsupportedOperationException(); }  // forced
}

Better: interface Printer { void print(); }, interface Scanner { void scan(); }, interface Fax { void fax(); }, and class OfficeMachine implements Printer, Scanner, Fax while BasicPrinter implements Printer only.

Problem 3: a copy that isn't a copy (shallow vs deep copy, immutability)

import java.util.ArrayList;

class Order {
    ArrayList<String> items = new ArrayList<>();
    Order() { }
    Order(Order other) {
        this.items = other.items;          // copies the reference
    }
}

public class Main {
    public static void main(String[] args) {
        Order mine = new Order();
        mine.items.add("biryani");
        Order friends = new Order(mine);   // "copy" my order
        friends.items.add("ice cream");
        System.out.println("mine:    " + mine.items);
        System.out.println("friends: " + friends.items);
    }
}

Output:

mine:    [biryani, ice cream]
friends: [biryani, ice cream]

The copy constructor copied the reference to the list, so both orders point to one list. Copying only the top-level fields, so inner objects are shared, is a shallow copy. Copying the inner objects too, so nothing is shared, is a deep copy:

import java.util.ArrayList;

class Order {
    ArrayList<String> items = new ArrayList<>();
    Order() { }
    Order(Order other) {
        this.items = new ArrayList<>(other.items);  // new list
    }
}

public class Main {
    public static void main(String[] args) {
        Order mine = new Order();
        mine.items.add("biryani");
        Order friends = new Order(mine);   // "copy" my order
        friends.items.add("ice cream");
        System.out.println("mine:    " + mine.items);
        System.out.println("friends: " + friends.items);
    }
}

Output:

mine:    [biryani]
friends: [biryani, ice cream]

Note: new ArrayList<>(other.items) makes a new list holding the same String objects. That's fine because Strings can't change (next section). If the items were mutable objects, a full deep copy would copy each item too.

In C++, the default copy constructor copies every member; for raw pointer members that is a shallow copy (two objects pointing to the same memory, later deleted twice). You write your own copy constructor to deep copy.

Immutable objects

An immutable object can never change after it's created, so sharing it is always safe.

final class Money {           // final: no sneaky children
    private final int rupees; // final: set once
    Money(int rupees) { this.rupees = rupees; }
    Money add(int more) {                 // returns a NEW object
        return new Money(rupees + more);
    }
    int rupees() { return rupees; }
}

public class Main {
    public static void main(String[] args) {
        String dish = "biryani";
        dish.toUpperCase();
        System.out.println(dish);
        Money price = new Money(200);
        Money withTip = price.add(20);
        System.out.println(price.rupees() + " " + withTip.rupees());
    }
}

Output:

biryani
200 220
  • String is immutable: toUpperCase() returns a new string; dish still says biryani. Fix: dish = dish.toUpperCase();.
  • Recipe for your own immutable class: make the class final (no child can add mutable behaviour), make every field private final, set fields only in the constructor, provide no setters, and return new objects from "changing" methods. If a field is a mutable object (like a list), copy it on the way in and on the way out.
  • Benefits: no shallow-copy surprises, safe to share between threads (parts of a program running at the same time, episode 20), safe as HashMap keys.

Problem 4: programs that crash (exceptions)

import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        FileReader f = new FileReader("menu.txt");
        System.out.println("opened");
    }
}

Output:

Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        FileReader f = new FileReader("menu.txt");
                       ^
1 error

An exception is an object Java creates and throws when something goes wrong at runtime (a missing file, a bad number, a null reference). If nobody catches it, the program stops and prints a stack trace (the list of method calls that led to the problem).

Real-life example: the airbag. You drive normally (try), a crash happens (an exception is thrown), the airbag opens (catch runs your plan), and the car is inspected after every trip, crash or not (finally).

import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {
    public static void main(String[] args) {
        try {
            FileReader f = new FileReader("menu.txt");   // checked
            System.out.println("opened");
        } catch (FileNotFoundException e) {
            System.out.println("No menu file: " + e.getMessage());
        }
        try {
            int qty = Integer.parseInt("two");          // unchecked
        } catch (NumberFormatException e) {
            System.out.println("Bad number: " + e.getMessage());
        } finally {
            System.out.println("finally always runs");
        }
    }
}

Output:

No menu file: menu.txt (No such file or directory)
Bad number: For input string: "two"
finally always runs
Keyword Meaning
try { } the risky code
catch (Type e) { } runs if an exception of that type (or a child type) is thrown in the try
finally { } always runs, exception or not; used to close files and connections
throw new X(...) throw an exception yourself: throw new IllegalArgumentException("amount must be > 0")
throws X in a method header: "I may throw X; my caller must handle it"
try-with-resources try (FileReader f = new FileReader("menu.txt")) { } closes f automatically

Checked vs unchecked exceptions

Throwable
├── Error                      (serious JVM problems: OutOfMemoryError, StackOverflowError; don't catch)
└── Exception
    ├── IOException, FileNotFoundException, SQLException ...   ← checked
    └── RuntimeException                                       ← unchecked
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        ├── ArithmeticException
        └── NumberFormatException (via IllegalArgumentException)
Checked exception Unchecked exception
Parent class Exception (but not RuntimeException) RuntimeException
Usually means a problem outside your control (file, network, database) a bug in your code
Compiler forces you to catch it or declare throws doesn't force anything
Examples FileNotFoundException, IOException NullPointerException, NumberFormatException

That's why the compiler demanded a plan for FileReader but said nothing about Integer.parseInt. C++ has exceptions too (try, catch, throw) but no checked exceptions.

Problem 5: wrong types sneak in (generics and templates)

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList prices = new ArrayList();  // no type: anything
        prices.add(120);
        prices.add(80);
        prices.add("free");                   // oops
        int total = 0;
        for (Object p : prices) {
            total += (Integer) p;
        }
        System.out.println(total);
    }
}

Output:

Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
    at Main.main(Main.java:11)

A list without a type (a raw type) accepts anything. The mistake on line 8 only blew up later, at runtime, as a ClassCastException.

Generics let you pass a type as a parameter. ArrayList<Integer> is a list that only accepts Integers, and the compiler checks it. You can write your own generic class: in Box<T>, T is a type parameter, a placeholder filled in when the class is used (Box<String>).

import java.util.ArrayList;

class Box<T> {              // T = any type, chosen later
    private T item;
    void put(T item) { this.item = item; }
    T get() { return item; }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> prices = new ArrayList<>();
        prices.add(120);
        prices.add(80);
        Box<String> b = new Box<>();
        b.put("biryani");
        System.out.println(prices + " " + b.get());
        prices.add("free");
    }
}

Output:

Main.java:17: error: incompatible types: String cannot be converted to Integer
        prices.add("free");
                   ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Caught at compile time. Without that line:

[120, 80] biryani

Notes: generics work only with object types, so you write ArrayList<Integer>, not ArrayList<int> (Java automatically converts between int and Integer, called autoboxing). Java removes the type parameters after checking (type erasure), so at runtime a Box<String> and a Box<Integer> are the same class.

Templates (C++)

#include <iostream>
#include <string>
using namespace std;

template <typename T>          // one recipe, any type
T biggest(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    cout << biggest(120, 80) << endl;
    cout << biggest(4.5, 9.25) << endl;
    cout << biggest(string("chai"), string("lassi")) << endl;
}

Output:

120
9.25
lassi

A template is C++'s version: a recipe the compiler uses to generate a separate function or class for each type you use (biggest<int>, biggest<double>, biggest<string>). "lassi" wins because l comes after c alphabetically.

Problem 6: trusted outsiders and cleanup (friend, garbage collection)

friend (C++)

#include <iostream>
using namespace std;

class Wallet {
    int balance = 500;                     // private
    friend void audit(const Wallet& w);    // trusted outsider
};

void audit(const Wallet& w) {
    cout << "Audited balance: " << w.balance << endl;
}

void hacker(const Wallet& w) {
    cout << w.balance << endl;
}

int main() {
    Wallet w;
    audit(w);
}

Output:

main.cpp: In function ‘void hacker(const Wallet&)’:
main.cpp:14:15: error: ‘int Wallet::balance’ is private within this context
   14 |     cout << w.balance << endl;
      |               ^~~~~~~
main.cpp:5:9: note: declared private here
    5 |     int balance = 500;                     // private
      |         ^~~~~~~

Remove hacker:

Audited balance: 500
  • A friend function is a non-member function that a class explicitly allows to access its private members (friend void audit(const Wallet& w);).
  • A friend class (friend class Auditor;) gives all of Auditor's methods that access.
  • Friendship is granted by the class, never taken; it is not inherited and not mutual. A common use is overloading operator<< for printing. Java has no friend; the closest is package-private (default) access.

Garbage collection basics

In Java, the garbage collector (GC) frees objects for you.

  • Garbage = an object that no reference can reach any more (Order o = new Order(); o = null; makes the first order garbage).
  • Roots = where the search starts: local variables on the stack of every running method, and static fields.
  • Mark and sweep: the GC marks every object reachable from the roots by following references, then sweeps, freeing everything unmarked. Modern JVMs add generations (most objects die young, so new objects are collected often and cheaply) and compaction (moving survivors together).
  • You can't choose when it runs; System.gc() is only a request. Objects referencing each other in a cycle are still collected if no root reaches them.
  • C++ has no GC: you free memory with delete, or better, let destructors and smart pointers (std::unique_ptr) do it.

Problem 7: design patterns

A design pattern is a named, reusable solution to a design problem that keeps coming up. Knowing the names lets a team say "use an observer here" instead of explaining the whole idea.

Singleton: exactly one instance

class Config {
    private static Config instance;        // the one and only
    private Config() { System.out.println("loading config..."); }
    static Config getInstance() {
        if (instance == null) instance = new Config();
        return instance;
    }
}

public class Main {
    public static void main(String[] args) {
        Config a = Config.getInstance();
        Config b = Config.getInstance();
        System.out.println(a == b);
        Config c = new Config();
    }
}

Output:

Main.java:15: error: Config() has private access in Config
        Config c = new Config();
                   ^
1 error

Without the illegal line:

loading config...
true

The private constructor stops anyone outside from calling new; the private static field holds the single instance; getInstance() creates it the first time (lazy initialisation) and returns the same one after that. Used for configuration, logging, connection pools. Caveat: this simple version isn't safe if two threads call getInstance() at the same moment; the easiest thread-safe version is private static final Config INSTANCE = new Config(); (created when the class loads) or an enum with one value.

Factory: one method decides which class to create

interface Notifier { void send(String msg); }
class SmsSender implements Notifier { public void send(String m) { System.out.println("SMS: " + m); } }
class EmailSender implements Notifier { public void send(String m) { System.out.println("Email: " + m); } }

class NotifierFactory {
    static Notifier create(String kind) {
        return switch (kind) {
            case "sms"   -> new SmsSender();
            case "email" -> new EmailSender();
            default      -> throw new IllegalArgumentException("unknown: " + kind);
        };
    }
}

public class Main {
    public static void main(String[] args) {
        NotifierFactory.create("email").send("order placed");
    }
}

Output:

Email: order placed

Callers ask for "email" and never write new EmailSender(), so adding a new kind changes only the factory.

Observer: notify every subscriber

import java.util.ArrayList;

interface Subscriber { void update(String video); }

class Channel {
    private final ArrayList<Subscriber> subs = new ArrayList<>();
    void subscribe(Subscriber s) { subs.add(s); }
    void upload(String video) {
        for (Subscriber s : subs) s.update(video);   // notify everyone
    }
}

public class Main {
    public static void main(String[] args) {
        Channel ch = new Channel();
        ch.subscribe(v -> System.out.println("Riya's phone: new video " + v));
        ch.subscribe(v -> System.out.println("Aman's email: new video " + v));
        ch.upload("OOP 3");
    }
}

Output:

Riya's phone: new video OOP 3
Aman's email: new video OOP 3

The subject (Channel) keeps a list of observers and calls them on every change; it doesn't know what they do. (v -> ... is a lambda, a short way to write an object with one method.)

Strategy: swap the algorithm at runtime

interface Discount { int apply(int bill); }

public class Main {
    static int checkout(int bill, Discount d) { return d.apply(bill); }
    public static void main(String[] args) {
        Discount none = b -> b;
        Discount festival = b -> b * 90 / 100;      // 10% off
        Discount flat50 = b -> Math.max(0, b - 50);
        System.out.println(checkout(400, none) + " " + checkout(400, festival) + " " + checkout(400, flat50));
    }
}

Output:

400 360 350

Each algorithm (here a discount rule) sits behind one interface and can be chosen at runtime. The Notifier demo was already a strategy.

Common mistakes (and the real output)

Mistake Real output Why Fix
Using java.util.Stack and calling list methods [sneaky, plate 2, plate 3] Stack extends Vector: inheritance leaks list methods composition, or ArrayDeque
Square extends Rectangle expected 20, got 16 the child breaks the parent's promises (LSP) a common Shape interface
this.items = other.items; in a copy constructor mine: [biryani, ice cream] shallow copy shares the list new ArrayList<>(other.items)
dish.toUpperCase(); and expecting dish to change biryani String is immutable dish = dish.toUpperCase();
new FileReader(...) with no try error: unreported exception FileNotFoundException; must be caught or declared to be thrown checked exception try/catch, or throws
Raw ArrayList with mixed types java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer no type check until runtime ArrayList<Integer>
Calling a private constructor of a singleton error: Config() has private access in Config the constructor is private on purpose Config.getInstance()
Reading a private member from a non-friend error: 'int Wallet::balance' is private within this context only members and friends may declare friend, or add a method

Mini project: a food-order service built the SOLID way

Combine composition, an interface, dependency injection, a checked exception, generics and a factory:

import java.util.ArrayList;
import java.util.List;

interface Notifier { void send(String msg); }
class SmsSender implements Notifier { public void send(String m) { System.out.println("SMS: " + m); } }
class EmailSender implements Notifier { public void send(String m) { System.out.println("Email: " + m); } }

class OutOfStockException extends Exception {          // checked: callers must handle it
    OutOfStockException(String item) { super(item + " is out of stock"); }
}

final class Order {                                     // immutable
    private final List<String> items;
    Order(List<String> items) { this.items = List.copyOf(items); }   // copy in
    List<String> items() { return items; }              // List.copyOf is already read-only
}

class OrderService {
    private final Notifier notifier;                    // has-a, injected
    private final List<String> stock = new ArrayList<>(List.of("biryani", "dosa"));
    OrderService(Notifier n) { notifier = n; }
    Order place(List<String> items) throws OutOfStockException {
        for (String i : items) if (!stock.contains(i)) throw new OutOfStockException(i);
        Order o = new Order(items);
        notifier.send("order placed: " + o.items());
        return o;
    }
}

public class Main {
    public static void main(String[] args) {
        OrderService svc = new OrderService(new EmailSender());
        try {
            svc.place(List.of("biryani", "dosa"));
            svc.place(List.of("pizza"));
        } catch (OutOfStockException e) {
            System.out.println("Sorry: " + e.getMessage());
        }
    }
}

Output:

Email: order placed: [biryani, dosa]
Sorry: pizza is out of stock

Extend it: add a WhatsAppSender without editing OrderService (OCP), and a NotifierFactory.

Practice

1. Add a WhatsAppSender without editing OrderService.

Solution
class WhatsAppSender implements Notifier {
    public void send(String m) { System.out.println("WhatsApp: " + m); }
}
// in main:
new OrderService(new WhatsAppSender()).placeOrder();   // prints WhatsApp: order placed

Only a new class was written: open for extension, closed for modification.

2. Make the Order class from the shallow-copy demo immutable.

Solution
final class Order {
    private final List<String> items;
    Order(List<String> items) { this.items = List.copyOf(items); }
    List<String> items() { return items; }
    Order with(String item) {                         // "adding" returns a new Order
        List<String> more = new ArrayList<>(items);
        more.add(item);
        return new Order(more);
    }
}

List.copyOf makes an unmodifiable copy, so neither the caller's list nor items() can change the order.

3. Write a generic Pair<A, B> class.

Solution
class Pair<A, B> {
    private final A first; private final B second;
    Pair(A first, B second) { this.first = first; this.second = second; }
    A first() { return first; }
    B second() { return second; }
}
// Pair<String, Integer> p = new Pair<>("biryani", 200);
// System.out.println(p.first() + " " + p.second());   → biryani 200

4. Aggregation or composition? (a) a library and its books, (b) a human and their heart, (c) a playlist and its songs, (d) an invoice and its line items.

Solution

(a) aggregation: books can move to another library. (b) composition. (c) aggregation: deleting a playlist doesn't delete the songs. (d) composition: line items have no meaning without their invoice.

5. Checked or unchecked? FileNotFoundException, NullPointerException, SQLException, ArithmeticException.

Solution

Checked: FileNotFoundException, SQLException. Unchecked: NullPointerException, ArithmeticException (both extend RuntimeException).

Quick quiz

try {
    int[] a = new int[2];
    a[5] = 1;
    System.out.print("A");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.print("B");
} finally {
    System.out.print("C");
}

A. AC B. BC C. ABC D. B

Answer

B. BC. a[5] throws before "A" prints, so control jumps to the catch (B); finally always runs (C).

Interview questions

  1. Composition vs inheritance: when do you use which? Inheritance for a true is-a where the child keeps all the parent's promises (LSP); composition (has-a) when you only want to reuse behaviour. Prefer composition: lower coupling, swappable parts, no leaked methods (Stack extends Vector).
  2. Aggregation vs composition? Both are has-a. Aggregation: parts can live without the whole (department–teachers). Composition: parts die with the whole (house–rooms).
  3. Abstraction vs encapsulation? Abstraction decides what to show (interfaces, abstract classes); encapsulation hides how by bundling data with methods and making data private.
  4. Explain SOLID with examples. See the table: one job per class; extend without editing; children substitutable for parents; small interfaces; depend on abstractions.
  5. What is tight coupling? How do you reduce it? A class depending on another's concrete details. Reduce it with interfaces and dependency injection.
  6. Shallow vs deep copy? Shallow copies the references (inner objects shared); deep copies the inner objects too.
  7. How do you make a class immutable? final class, private final fields, no setters, set in constructor, defensive copies of mutable fields, return new objects for changes.
  8. Checked vs unchecked exceptions? Checked must be caught or declared (IOException); unchecked extend RuntimeException and usually signal bugs (NullPointerException).
  9. final vs finally vs finalize? final: can't change/override/extend. finally: block that always runs after try/catch. finalize(): an old, deprecated method the GC might call before freeing an object; don't use it.
  10. Does finally run if the try block returns? Yes, finally runs before the method actually returns (only stopping the JVM, e.g. System.exit, skips it).
  11. Why generics? Type safety at compile time and no casts; one class works for many types.
  12. What is a friend function? Does Java have one? A non-member function a C++ class allows to access its private members. Java has no friend; package-private access is the nearest idea.
  13. How does garbage collection decide what to free? Objects not reachable from the roots (stack variables, statics) are garbage; mark and sweep frees them.
  14. Implement a singleton. Is it thread-safe? Private constructor, private static instance, static getInstance(). The lazy version isn't thread-safe; use eager initialisation, a synchronized/double-checked version, or an enum.
  15. Name the design patterns you know and where you'd use them. Singleton (config/logger), factory (create objects by kind), observer (notifications, event listeners), strategy (interchangeable algorithms like discount or payment rules).

Glossary

Term Meaning in plain words Example
is-a A child is a kind of parent: the test for inheritance a savings account is an account
has-a One object holds another as a field a car has an engine
Association Two objects know and use each other, each living independently teacher and students
Aggregation Weak has-a: parts can exist without the whole department and teachers
Composition Strong has-a: parts are owned by and die with the whole house and rooms; PlateStack and its list
Composition over inheritance Prefer holding an object as a field over extending its class PlateStack vs Stack extends Vector
Stack (data structure) A pile where you add and remove only at the top (LIFO) plates
Abstraction Showing only essential operations, hiding complexity push/pop
Encapsulation Bundling data with its methods and hiding the data private ArrayList list
Coupling How much one class depends on another's details OrderService → SmsSender
Cohesion How focused one class is on a single job OrderService only handles orders
Dependency An object another object needs to do its job the Notifier of OrderService
Dependency injection Handing an object its dependencies from outside new OrderService(new SmsSender())
SOLID Five design principles: SRP, OCP, LSP, ISP, DIP —
Single Responsibility Principle (SRP) One class, one job, one reason to change orders vs notifications
Open/Closed Principle (OCP) Open for extension, closed for modification add EmailSender, edit nothing
Liskov Substitution Principle (LSP) A child must work anywhere the parent works Square breaks it
Interface Segregation Principle (ISP) Prefer small interfaces; never force unused methods Printer, Scanner, Fax
Dependency Inversion Principle (DIP) Depend on abstractions, not concrete classes OrderService → Notifier
Shallow copy Copies top-level fields; inner objects are shared this.items = other.items
Deep copy Copies inner objects too; nothing shared new ArrayList<>(other.items)
Immutable object An object that can't change after creation String, our Money
Exception An object thrown when something goes wrong at runtime FileNotFoundException
Throw Create and raise an exception throw new IllegalArgumentException()
try / catch / finally Risky code / plan for an exception / code that always runs the airbag story
throws A method header saying it may throw a checked exception void load() throws IOException
Stack trace The list of method calls printed when an exception isn't caught at Main.main(Main.java:11)
Checked exception Must be caught or declared; outside problems IOException
Unchecked exception A RuntimeException; usually a bug; not forced NullPointerException
Error (Java) A serious JVM problem you shouldn't catch OutOfMemoryError
Raw type A generic class used without a type argument ArrayList prices
Generics Classes and methods that take a type as a parameter ArrayList<Integer>
Type parameter The placeholder type in a generic class T in Box<T>
Autoboxing Automatic conversion between int and Integer prices.add(120)
Type erasure Java removes generic types after checking them Box<String> and Box<Integer> share a class
Template (C++) A recipe the compiler turns into code for each type template <typename T>
Friend function / class A non-member C++ function or class allowed to access private members friend void audit(...)
Garbage collector (GC) Part of the JVM that frees unreachable objects —
Garbage An object no reference can reach after o = null;
Roots Where the GC starts searching: stack variables, statics —
Mark and sweep Mark reachable objects, free the rest —
Design pattern A named, reusable solution to a common design problem singleton
Singleton A class with exactly one instance and a global access point Config.getInstance()
Lazy initialisation Creating something only when it's first needed if (instance == null) ...
Factory A method or class that decides which class to instantiate NotifierFactory.create("sms")
Observer Subscribers are notified of every change in a subject channel and subscribers
Strategy Interchangeable algorithms behind one interface discount rules
Lambda A short way to write an object with one method b -> b * 90 / 100

Summary

  • Inherit only for a true is-a; otherwise use has-a (composition over inheritance). Stack extends Vector is the classic leak. Objects relate by association, aggregation (weak) or composition (strong).
  • Abstraction chooses what to show; encapsulation hides how.
  • Aim for low coupling, high cohesion. Depend on interfaces and inject dependencies. SOLID: one job per class, extend without editing, substitutable children, small interfaces, depend on abstractions.
  • A shallow copy shares inner objects; a deep copy doesn't; immutable objects make sharing safe.
  • Exceptions: try/catch/finally, throw/throws; checked ones are forced by the compiler, unchecked ones are usually bugs.
  • Generics (Java) and templates (C++) move type mistakes to compile time.
  • C++ friend grants private access; Java's garbage collector frees unreachable objects by mark and sweep.
  • Design patterns: singleton, factory, observer, strategy.

Outside facts: that java.util.Stack extends java.util.Vector is printed live by the JDK in the first demo; the advice to prefer Deque comes from the Stack API documentation.

Next episode: Operating systems: what an OS does: the kernel, user mode vs kernel mode, system calls, interrupts and the types of OS.