Find a lesson, question or project

Start typing to search published content and planned structures.

↑ ↓ moveEnter openEsc close

Java OOP for LLD, Part 2: Four Pillars, Relationships, and Generics

Learn Java encapsulation, abstraction, inheritance, polymorphism, access modifiers, class relationships, generics, and wildcards through the MealFlow design.

BasicsLLD

Learn how encapsulation, abstraction, inheritance, polymorphism, class relationships, access control, and generics work together in real LLD interviews.

Insight

Start with Java OOP for LLD: Classes, Objects, Constructors, and this for Part 1.

In the previous part of this series, we built the foundation of Object-Oriented Programming with classes, objects, constructors, references, copying, and the this keyword.

Now our design is ready to grow.

Imagine that we are building MealFlow, a food-delivery platform. A customer places an order, a restaurant prepares it, a payment provider collects money, a delivery partner carries the food, and a notification channel keeps the customer informed. 🍔📦🛵

At first, this sounds like a collection of simple classes. But real questions appear very quickly:

  • Who is allowed to change an order’s status?
  • How can card, UPI, and wallet payments share one checkout flow?
  • Should every delivery partner inherit from the same parent?
  • How can one notification operation work for email, SMS, and push notifications?
  • Does an order own its order lines?
  • When should a field be private, protected, or package-private?
  • How can one repository work safely with many entity types?

These are not separate Java puzzles. They are design decisions—and this is where the real power of OOP begins.

Notebook-style Java OOP and MealFlow overview


🎯 Why These Concepts Matter in LLD Interviews

An interviewer rarely asks only, “What is polymorphism?” and stops there.

Instead, you may be asked to design a food-delivery platform, parking lot, elevator, notification service, or ticket-booking system. While you design it, the interviewer quietly evaluates whether you can:

  1. protect an object’s valid state,
  2. separate a contract from its implementation,
  3. recognize a genuine is-a relationship,
  4. replace one implementation without changing client code,
  5. model ownership and collaboration correctly,
  6. expose only the access that other classes actually need, and
  7. build reusable APIs without losing type safety.

The four pillars give us the vocabulary. Good LLD comes from knowing when to use each pillar—and when not to.

Warning

Interview mindset: Do not add inheritance, interfaces, or generic types merely to make a design look advanced. Every abstraction should solve a real problem in the requirements.


🧭 Our Story: One Order Moving Through MealFlow

We will follow one order through the system:

  1. A customer adds meals and confirms the order.
  2. MealFlow collects payment through one of several payment providers.
  3. The restaurant prepares the order.
  4. A suitable delivery partner accepts it.
  5. The platform sends updates through email, SMS, or push notifications.

The journey stays the same, but each OOP concept helps us design one part correctly.

Notebook-style MealFlow learning map


Part I — The Four Pillars of OOP

1. 🔒 Encapsulation: Protect the Object’s Rules

Encapsulation means placing related state and behavior inside one class and controlling how the outside world interacts with that state.

The simplest version is often described as “make fields private and add getters and setters.” That description is incomplete.

Real encapsulation is about protecting invariants—rules that must always remain true.

For a food order, these rules might be:

  • an empty order cannot be confirmed,
  • an item cannot be added after confirmation,
  • a delivered order cannot return to preparation,
  • the total must match the order lines, and
  • external code must not assign any status it wants.

⚠️ The Problem Without Encapsulation

Java
class FoodOrder {
    public String status;
    public long totalInPaise;
}

public class Main {
    public static void main(String[] args) {
        FoodOrder order = new FoodOrder();

        // The object cannot protect itself.
        order.status = "DELIVERED";
        order.totalInPaise = -50_000;
    }
}

The code compiles, but the object now represents an impossible business state.

✅ A Better Encapsulated Design

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

enum OrderStatus {
    DRAFT,
    CONFIRMED,
    PREPARING,
    OUT_FOR_DELIVERY,
    DELIVERED,
    CANCELLED
}

final class OrderLine {
    private final String itemName;
    private final int quantity;
    private final long unitPriceInPaise;

    OrderLine(String itemName, int quantity, long unitPriceInPaise) {
        if (itemName == null || itemName.trim().isEmpty()) {
            throw new IllegalArgumentException("Item name is required");
        }
        if (quantity <= 0 || unitPriceInPaise < 0) {
            throw new IllegalArgumentException("Invalid order line");
        }

        this.itemName = itemName;
        this.quantity = quantity;
        this.unitPriceInPaise = unitPriceInPaise;
    }

    long subtotalInPaise() {
        return unitPriceInPaise * quantity;
    }
}

class FoodOrder {
    private final String orderId;
    private final List<OrderLine> lines = new ArrayList<>();
    private OrderStatus status = OrderStatus.DRAFT;

    FoodOrder(String orderId) {
        if (orderId == null || orderId.trim().isEmpty()) {
            throw new IllegalArgumentException("Order ID is required");
        }
        this.orderId = orderId;
    }

    void addItem(OrderLine line) {
        ensureStatus(OrderStatus.DRAFT);
        lines.add(line);
    }

    void confirm() {
        ensureStatus(OrderStatus.DRAFT);
        if (lines.isEmpty()) {
            throw new IllegalStateException("Cannot confirm an empty order");
        }
        status = OrderStatus.CONFIRMED;
    }

    void startPreparation() {
        ensureStatus(OrderStatus.CONFIRMED);
        status = OrderStatus.PREPARING;
    }

    long totalInPaise() {
        long total = 0;
        for (OrderLine line : lines) {
            total += line.subtotalInPaise();
        }
        return total;
    }

    List<OrderLine> lines() {
        // Callers can inspect the list but cannot mutate our collection.
        return Collections.unmodifiableList(lines);
    }

    OrderStatus status() {
        return status;
    }

    private void ensureStatus(OrderStatus expected) {
        if (status != expected) {
            throw new IllegalStateException(
                    "Expected " + expected + " but was " + status
            );
        }
    }
}

Notice what this class does not provide:

Java
void setStatus(OrderStatus status)
void setTotalInPaise(long total)

Those setters would allow callers to bypass the business rules. Instead, the class exposes meaningful operations such as addItem(), confirm(), and startPreparation().

🔍 Encapsulation vs. Data Hiding

These ideas are closely related, but they are not identical:

  • Data hiding restricts direct access to implementation details.
  • Encapsulation groups state and behavior behind a controlled public API.

Making a field private provides data hiding. Designing operations that protect the object’s invariants provides meaningful encapsulation.

🧰 Other Encapsulation Techniques

Private fields are only the beginning. We can also use:

  • immutable objects,
  • defensive copies,
  • unmodifiable collection views,
  • validation in constructors and methods,
  • package-private implementation classes,
  • narrow interfaces, and
  • value objects that validate themselves.

🎯 Why It Matters in LLD

An object that protects its own state is easier to reason about. Callers do not need to remember every legal transition because the object rejects illegal ones.

Encapsulation also gives us freedom to change the internal representation. We could later calculate the total using discounts and taxes without changing how callers confirm an order.

Notebook-style encapsulation illustration

🎤 Encapsulation Interview Questions

1. Is encapsulation just private fields with getters and setters?

No. Private fields restrict direct access, but unrestricted getters and setters can still expose the entire representation. Encapsulation means providing an API that preserves the object’s rules and hides unnecessary implementation details.

2. Why is setStatus() often a poor method for an order?

It allows any caller to perform any transition. Domain operations such as confirm(), cancel(), and markDelivered() communicate intent and can validate whether the transition is legal.

3. What is an invariant?

An invariant is a condition that must remain true for an object to be valid. For example, a confirmed order must contain at least one item.

4. Does returning a private collection through a getter preserve encapsulation?

Not if the caller receives the mutable collection itself. The caller could modify internal state without using the object’s rules. Return an unmodifiable view or a defensive copy when appropriate.

5. Does encapsulation provide application security?

It prevents accidental or unsupported access through normal Java code, but it does not replace authentication, authorization, input validation, or other security controls.

6. Can an immutable object be encapsulated?

Yes. Immutability is a strong encapsulation technique because valid state is established during construction and cannot be changed afterward.

7. What is the best short interview definition?

Insight

Encapsulation combines state and behavior behind a controlled API so that an object can protect its invariants and hide implementation details.


2. 🎭 Abstraction: Expose the What, Hide the How

Abstraction lets a caller work with an essential capability without knowing every implementation detail behind it.

When MealFlow checks out an order, it should understand one business operation:

Text
pay for this order

It should not need to understand card-network calls, UPI handles, wallet balances, signatures, retries, or provider-specific response formats.

⚠️ The Problem Without Abstraction

Java
class CheckoutService {

    void checkout(FoodOrder order, String paymentType) {
        if ("CARD".equals(paymentType)) {
            // Card-provider-specific logic
            System.out.println("Calling card network");
        } else if ("UPI".equals(paymentType)) {
            // UPI-provider-specific logic
            System.out.println("Calling UPI provider");
        } else if ("WALLET".equals(paymentType)) {
            // Wallet-provider-specific logic
            System.out.println("Checking wallet balance");
        }
    }
}

Every new payment method forces us to modify CheckoutService. The class is tightly coupled to all payment details.

✅ Solution: Depend on a Contract

Java
final class PaymentRequest {
    private final String orderId;
    private final long amountInPaise;

    PaymentRequest(String orderId, long amountInPaise) {
        this.orderId = orderId;
        this.amountInPaise = amountInPaise;
    }

    String orderId() {
        return orderId;
    }

    long amountInPaise() {
        return amountInPaise;
    }
}

final class PaymentReceipt {
    private final String transactionId;

    PaymentReceipt(String transactionId) {
        this.transactionId = transactionId;
    }

    String transactionId() {
        return transactionId;
    }
}

interface PaymentProcessor {
    PaymentReceipt pay(PaymentRequest request);
}

class CardPaymentProcessor implements PaymentProcessor {
    @Override
    public PaymentReceipt pay(PaymentRequest request) {
        System.out.println("Processing card payment");
        return new PaymentReceipt("CARD-TXN-101");
    }
}

class UpiPaymentProcessor implements PaymentProcessor {
    @Override
    public PaymentReceipt pay(PaymentRequest request) {
        System.out.println("Processing UPI payment");
        return new PaymentReceipt("UPI-TXN-202");
    }
}

class CheckoutService {
    private final PaymentProcessor paymentProcessor;

    CheckoutService(PaymentProcessor paymentProcessor) {
        this.paymentProcessor = paymentProcessor;
    }

    PaymentReceipt checkout(String orderId, long amountInPaise) {
        PaymentRequest request =
                new PaymentRequest(orderId, amountInPaise);

        return paymentProcessor.pay(request);
    }
}

CheckoutService knows what a payment processor can do. It does not know how the processor communicates with its provider.

This is abstraction—and it also supports dependency inversion because the checkout flow depends on a contract rather than a concrete provider.

🪟 Abstraction Does Not Mean “Hide Everything”

A good abstraction reveals the information a caller needs and hides the details it does not.

If the abstraction is too broad, implementations are forced to support irrelevant operations. If it is too narrow, callers may need to understand implementation details again.

The goal is a stable, meaningful contract.

Notebook-style abstraction illustration

🧱 Abstract Class: Shared Identity, State, and Behavior

An abstract class is useful when closely related classes share state or implementation and also require specialized behavior.

Java
abstract class DeliveryPartner {
    private final String partnerId;
    private boolean available = true;

    DeliveryPartner(String partnerId) {
        this.partnerId = partnerId;
    }

    final void acceptDelivery(String orderId) {
        if (!available) {
            throw new IllegalStateException("Partner is already busy");
        }
        available = false;
        System.out.println(partnerId + " accepted " + orderId);
    }

    abstract int estimatedMinutes(int distanceInKm);

    protected final String partnerId() {
        return partnerId;
    }
}

class BikeDeliveryPartner extends DeliveryPartner {
    BikeDeliveryPartner(String partnerId) {
        super(partnerId);
    }

    @Override
    int estimatedMinutes(int distanceInKm) {
        return 10 + (distanceInKm * 4);
    }
}

An abstract class:

  • cannot be instantiated directly,
  • may have constructors,
  • may hold mutable or immutable instance state,
  • may contain abstract and concrete methods,
  • may use all normal method-access levels, and
  • may contain no abstract methods at all if its purpose is only to prevent direct instantiation.

Its constructor still runs when a concrete subclass is created.

🔌 Interface: A Capability or Contract

An interface is useful when different classes must offer the same capability, especially when they do not belong to one natural class hierarchy.

Java
interface NotificationChannel {
    void send(String destination, String message);

    default boolean supportsUrgentMessages() {
        return false;
    }

    static String normalize(String message) {
        return message == null ? "" : message.trim();
    }
}

class EmailChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("Email to " + destination + ": "
                + NotificationChannel.normalize(message));
    }
}

class PushChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("Push to " + destination + ": "
                + NotificationChannel.normalize(message));
    }

    @Override
    public boolean supportsUrgentMessages() {
        return true;
    }
}

Modern Java interfaces can contain:

  • abstract methods,
  • default methods since Java 8,
  • static methods since Java 8,
  • private helper methods since Java 9, and
  • public static final constants.

They cannot hold ordinary per-object instance state or declare constructors.

Think of NotificationChannel as MealFlow’s promise: every notification channel can send a message. Email and push notifications keep that promise in different ways.

An interface can also provide useful shared behavior and helpers. Let us separate their roles so they are easy to remember. 💡

🧰 Interface Methods: What Changed in Java 8 and Java 9?

🔁 default Methods — Shared Behavior Since Java 8

A default method has a body inside the interface. An implementing class can use that implementation or override it when its behavior differs.

In the example above, EmailChannel inherits supportsUrgentMessages() and returns false. PushChannel overrides it and returns true.

Java
NotificationChannel email = new EmailChannel();
NotificationChannel push = new PushChannel();

System.out.println(email.supportsUrgentMessages()); // false
System.out.println(push.supportsUrgentMessages());  // true

This is an instance method: the call goes through an object. It can call other methods in the interface, including send(...), whose implementation is supplied by the class.

Default methods can help an interface evolve without immediately requiring every implementation to write a new method. Still, adding one needs care: conflicting defaults or changed expectations can affect existing clients. See Oracle’s Java 8 interface tutorial.

🛠️ static Methods — Interface-Level Helpers Since Java 8

A static method belongs to the interface itself. You call it using the interface name, without creating an object.

MealFlow’s normalize(...) helper removes surrounding spaces from a message:

Java
String message = NotificationChannel.normalize("  Your order is ready!  ");
System.out.println(message); // Your order is ready!

Call it as NotificationChannel.normalize(...), not EmailChannel.normalize(...) or email.normalize(...). Interface static methods are not inherited by implementing classes or subinterfaces, and they are not overridden like instance methods.

Use one for a helper or factory closely related to the interface. Do not turn the interface into a collection of unrelated utilities. Java 8 introduced interface static methods alongside default methods. See Oracle’s interface-method explanation.

🔒 private Methods — Internal Helpers Since Java 9

Suppose two default methods need the same message-formatting logic. Copying that logic into both methods creates duplication. Making the helper public would expose a detail callers do not need.

A private interface method solves this: it shares implementation inside the interface, without adding another public capability. Here is a standalone example that runs on Java 9 or later:

Java
interface NotificationChannel {
    void send(String destination, String message);

    default void sendOrderConfirmed(String destination, String orderId) {
        send(destination, formatOrderMessage(orderId, "confirmed"));
    }

    default void sendOutForDelivery(String destination, String orderId) {
        send(destination, formatOrderMessage(orderId, "out for delivery"));
    }

    // Private instance helper: shared by the two default methods.
    private String formatOrderMessage(String orderId, String status) {
        return "Order " + normalize(orderId) + " is " + status + ".";
    }

    // Public static helper: callers use NotificationChannel.normalize(...).
    static String normalize(String value) {
        return trimOrEmpty(value);
    }

    // Private static helper: used internally by the static method.
    private static String trimOrEmpty(String value) {
        return value == null ? "" : value.trim();
    }
}

class EmailChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("Email to " + destination + ": " + message);
    }
}

public class InterfaceMethodsDemo {
    public static void main(String[] args) {
        NotificationChannel channel = new EmailChannel();
        channel.sendOrderConfirmed("reader@example.com", "  MF-101  ");
        channel.sendOutForDelivery("reader@example.com", "MF-101");
    }
}

Output:

Text
Email to reader@example.com: Order MF-101 is confirmed.
Email to reader@example.com: Order MF-101 is out for delivery.

The private instance helper supports the default methods. The private static helper supports the static method. Neither helper is available to callers, inherited by implementations, or overridden by them. A static method cannot directly call a private instance helper without an interface instance. These private helpers must have method bodies; they cannot be abstract. See the Java 9 language specification.

This example demonstrates message formatting, not a real email integration. MealFlow must validate order identifiers and destinations at its application boundary; trimming text is not business validation.

🧠 Remember the three jobs: default gives objects shared behavior. static gives the interface a related helper. private keeps shared implementation details inside the interface.

⚖️ Abstract Class or Interface?

Start with a simple question: do these objects need a shared foundation, or do they only need to offer the same capability?

🧱 Choose an Abstract Class for a Shared Foundation

MealFlow’s bike and van delivery partners belong to the same delivery-partner family. Both may need a partner ID, availability state, and common rules for accepting a delivery.

An abstract class is a useful choice when:

  • the classes are closely related,
  • they need shared per-object data, such as partnerId and available,
  • a common constructor should initialize that data,
  • subclasses need protected methods to customize part of the behavior, or
  • meaningful shared implementation belongs in the parent.

The parent gives the family a common starting point. Each child adds its specialized behavior—for example, estimating delivery time for a bike or a van. 🚲🚐

🔌 Choose an Interface for a Capability

An email channel and a push channel do not need the same instance fields or constructor. They simply need to provide MealFlow’s notification capability.

An interface is a useful choice when:

  • you want to describe what an object can do,
  • different kinds of classes can offer that capability,
  • one class may need several capabilities,
  • callers should use a contract without knowing the implementation, or
  • implementations should be replaceable while preserving the contract.

The caller can use NotificationChannel without caring whether the message travels through email or push. 📩

🤝 Sometimes You Need Both

A delivery partner can share the DeliveryPartner foundation and also provide tracking and contact capabilities. Java allows a class to extend one class and implement several interfaces.

This example builds on the DeliveryPartner abstract class introduced earlier:

Java
interface Trackable {
    String currentLocation();
}

interface Contactable {
    void contact(String message);
}

class ConnectedBikePartner extends DeliveryPartner
        implements Trackable, Contactable {
    private final String location;

    ConnectedBikePartner(String partnerId, String location) {
        super(partnerId);
        this.location = location;
    }

    @Override
    int estimatedMinutes(int distanceInKm) {
        return 10 + distanceInKm * 4;
    }

    @Override
    public String currentLocation() {
        return location;
    }

    @Override
    public void contact(String message) {
        System.out.println("Message to " + partnerId() + ": " + message);
    }
}

The abstract class supplies shared state and delivery behavior. The interfaces describe two additional capabilities. The fixed location and console message keep this example small; real tracking and messaging would use their own collaborators.

🎯 Simple decision rule: Shared family, state, and construction? Consider an abstract class. Shared capability across different types? Consider an interface. Need both? Combine them. Do not create inheritance only to reuse a few lines.

🧩 Default-Method Resolution Rules

When defaults collide, remember these rules:

  1. A concrete method inherited from a class wins over an interface default.
  2. A more specific interface wins over a less specific parent interface.
  3. Unrelated interfaces with conflicting defaults require an explicit override.
Java
interface CustomerNotifier {
    default void sendStatus() {
        System.out.println("Customer notification");
    }
}

interface RestaurantNotifier {
    default void sendStatus() {
        System.out.println("Restaurant notification");
    }
}

class OrderNotifier
        implements CustomerNotifier, RestaurantNotifier {

    @Override
    public void sendStatus() {
        CustomerNotifier.super.sendStatus();
        RestaurantNotifier.super.sendStatus();
    }
}

A default method may also be re-declared as abstract by a subinterface:

Java
interface Auditable {
    default void audit() {
        System.out.println("Basic audit");
    }
}

interface StrictlyAuditable extends Auditable {
    @Override
    void audit(); // Re-abstracts the inherited default method
}

🚧 Avoid Over-Abstraction

An interface is valuable when it creates a useful boundary. An interface with one implementation and no realistic reason to vary may only add navigation and mental overhead.

Follow YAGNI: You Aren’t Gonna Need It. Add abstraction when the design has a real point of variation, external boundary, test seam, or capability—not because every class “should” have an interface.

🎤 Abstraction Interview Questions

1. What is abstraction?

Abstraction exposes the essential behavior a caller needs while hiding unnecessary implementation details.

2. How is abstraction different from encapsulation?

Abstraction decides which essential view or contract to expose. Encapsulation protects an object’s state and implementation behind controlled boundaries. They often work together.

3. Can an abstract class have no abstract methods?

Yes. Marking it abstract can prevent direct instantiation even when all of its methods are concrete.

4. Why can an abstract class have a constructor?

The constructor initializes the superclass portion of a concrete subclass object. It runs through super(...) during subclass construction.

5. Can an abstract class implement an interface without implementing every method?

Yes. Because the class is abstract, it may leave some interface methods for concrete subclasses to implement.

6. What is the main difference between an abstract class and an interface?

An abstract class can represent shared identity, instance state, construction, and implementation. An interface primarily defines a capability or contract that many types can implement.

7. Why were default interface methods introduced?

They allow an interface to add compatible behavior without immediately forcing every existing implementation to define the new method. They were important for evolving collection APIs in Java 8.

8. Can a class ignore a default method?

Yes. It inherits the default unless a class method takes priority or a conflict requires resolution. It may also override the default.

9. Can a default method access an implementing object’s state?

It cannot declare or directly assume arbitrary instance fields, but it can call interface methods implemented by the object, and those methods may use the object’s state.

10. Can a default method be made abstract again?

Yes. A subinterface or abstract class may re-declare it as abstract and require a more specific implementation.

11. What happens when two unrelated interfaces provide the same default method?

The implementing class must override the method and resolve the ambiguity explicitly.

12. What is the danger of over-abstraction?

It adds indirection, more files, harder navigation, and contracts that may not represent real variation. The design becomes harder without gaining flexibility.


3. 🌳 Inheritance: Model a Real “Is-A” Relationship

Inheritance allows one class to acquire accessible behavior from another class and specialize it.

In Java, a class uses extends to inherit from one superclass.

Java
class BikeDeliveryPartner extends DeliveryPartner {
    // BikeDeliveryPartner is a DeliveryPartner.
}

The most important phrase is not “reuse code.” It is:

Insight

A subclass must genuinely be usable as its superclass.

If BikeDeliveryPartner extends DeliveryPartner, every place that accepts a DeliveryPartner should safely accept a BikeDeliveryPartner.

That is the practical heart of the Liskov Substitution Principle.

✅ A Valid Inheritance Hierarchy

Java
abstract class DeliveryPartner {
    private final String partnerId;

    DeliveryPartner(String partnerId) {
        this.partnerId = partnerId;
    }

    String partnerId() {
        return partnerId;
    }

    abstract int estimatedMinutes(int distanceInKm);
}

class BikeDeliveryPartner extends DeliveryPartner {
    BikeDeliveryPartner(String partnerId) {
        super(partnerId);
    }

    @Override
    int estimatedMinutes(int distanceInKm) {
        return 8 + (distanceInKm * 4);
    }
}

class CarDeliveryPartner extends DeliveryPartner {
    CarDeliveryPartner(String partnerId) {
        super(partnerId);
    }

    @Override
    int estimatedMinutes(int distanceInKm) {
        return 12 + (distanceInKm * 3);
    }
}

Both subclasses preserve the meaning of a delivery partner while specializing travel-time calculation.

🧬 Types of Inheritance in Java

1. Single Inheritance

One subclass extends one superclass:

Java
class BikeDeliveryPartner extends DeliveryPartner {
}

Java allows a class to extend only one direct superclass.

2. Multilevel Inheritance

Inheritance forms a chain:

Java
abstract class DeliveryPartner {
}

abstract class MotorizedDeliveryPartner extends DeliveryPartner {
}

class BikeDeliveryPartner extends MotorizedDeliveryPartner {
}

This is legal, but deep chains become difficult to understand and change. Prefer shallow hierarchies.

3. Hierarchical Inheritance

Several subclasses extend one superclass:

Java
class BikeDeliveryPartner extends DeliveryPartner {
}

class CarDeliveryPartner extends DeliveryPartner {
}

class WalkingDeliveryPartner extends DeliveryPartner {
}

Each child shares the parent’s contract and adds its own specialization.

4. Multiple Inheritance Through Interfaces

Java does not allow a class to extend multiple classes, but a class may implement several interfaces:

Java
interface Trackable {
    String currentLocation();
}

interface BackgroundVerified {
    boolean isVerified();
}

class BikeDeliveryPartner extends DeliveryPartner
        implements Trackable, BackgroundVerified {

    BikeDeliveryPartner(String partnerId) {
        super(partnerId);
    }

    @Override
    int estimatedMinutes(int distanceInKm) {
        return 8 + (distanceInKm * 4);
    }

    @Override
    public String currentLocation() {
        return "Sector 12";
    }

    @Override
    public boolean isVerified() {
        return true;
    }
}

This is sometimes described as multiple inheritance of type or behavior. It is not multiple inheritance of ordinary mutable class state.

5. Hybrid Inheritance

“Hybrid inheritance” is a teaching term for combining class inheritance with multiple interfaces, as the previous example does. It is not a separate Java language feature.

💎 Why Java Avoids Multiple Class Inheritance

Suppose two parent classes provide the same method and one child extends both. Which implementation should the child inherit?

That ambiguity is commonly illustrated as the diamond problem.

Java avoids the problem by allowing only one superclass. Interfaces can still provide multiple capabilities, and conflicting default methods must be resolved explicitly by the implementing class.

🔁 Constructor Order in an Inheritance Chain

Constructors are not inherited, but superclass construction still happens first. Java inserts super() as the first statement when a constructor does not call another constructor explicitly.

Java
class DeliveryPartner {
    DeliveryPartner() {
        System.out.println("DeliveryPartner initialized");
    }
}

class BikeDeliveryPartner extends DeliveryPartner {
    BikeDeliveryPartner() {
        System.out.println("BikeDeliveryPartner initialized");
    }
}

public class Main {
    public static void main(String[] args) {
        new BikeDeliveryPartner();
    }
}

Output:

Text
DeliveryPartner initialized
BikeDeliveryPartner initialized

This order guarantees that the inherited part of the object is initialized before the subclass adds its own state.

Notebook-style inheritance and diamond problem illustration

🚫 The Wrong Reason to Use Inheritance

Code reuse alone is not enough.

Imagine we create this hierarchy:

Java
abstract class DeliveryPartner {
    abstract void driveVehicle();
}

class WalkingDeliveryPartner extends DeliveryPartner {
    @Override
    void driveVehicle() {
        throw new UnsupportedOperationException(
                "Walking partners do not drive"
        );
    }
}

The subclass cannot honor its parent’s contract. That is a design smell.

A better model keeps the valid delivery hierarchy and separates the optional capability:

Java
abstract class DeliveryPartner {
    abstract void deliver(String orderId);
}

interface Motorized {
    void startVehicle();
}

class WalkingDeliveryPartner extends DeliveryPartner {
    @Override
    public void deliver(String orderId) {
        System.out.println("Walking delivery for " + orderId);
    }
}

class BikeDeliveryPartner extends DeliveryPartner
        implements Motorized {

    @Override
    public void deliver(String orderId) {
        System.out.println("Bike delivery for " + orderId);
    }

    @Override
    public void startVehicle() {
        System.out.println("Bike started");
    }
}

Now each class promises only behavior it can actually provide.

🔄 Inheritance vs. Composition

Inheritance models is-a:

Text
BikeDeliveryPartner is a DeliveryPartner.

Composition models has-a:

Text
DeliveryService has a RoutePlanner.

Composition is often more flexible because behavior can be replaced without changing the class hierarchy.

Java
interface RoutePlanner {
    int estimateMinutes(int distanceInKm);
}

class CityRoutePlanner implements RoutePlanner {
    @Override
    public int estimateMinutes(int distanceInKm) {
        return 10 + (distanceInKm * 3);
    }
}

class DeliveryService {
    private final RoutePlanner routePlanner;

    DeliveryService(RoutePlanner routePlanner) {
        this.routePlanner = routePlanner;
    }
}

DeliveryService does not become a route planner. It collaborates with one.

🌱 Benefits of Inheritance

  • It expresses a meaningful taxonomy.
  • It supports runtime polymorphism.
  • It centralizes behavior that truly belongs to the whole family.
  • It lets subclasses specialize behavior.

⚠️ Risks of Inheritance

  • Subclasses become coupled to superclass decisions.
  • A superclass change may affect many children.
  • Deep hierarchies are difficult to navigate.
  • Incorrect hierarchies force irrelevant methods onto subclasses.
  • Overriding can break assumptions made by the superclass.
  • Fragile base classes can spread bugs through the hierarchy.

Use inheritance when the semantic relationship is strong and stable. Prefer composition when you mainly want to assemble or replace behavior.

🎤 Inheritance Interview Questions

1. What is inheritance?

Inheritance lets a subclass acquire accessible behavior from a superclass and specialize it, representing a genuine is-a relationship.

2. Does Java support multiple inheritance?

Java does not support extending multiple classes. A class may implement multiple interfaces, which provides multiple inheritance of contracts and possibly default behavior.

3. What is the diamond problem?

It is the ambiguity that occurs when a child inherits conflicting implementations through multiple paths. Java avoids multiple class inheritance and requires explicit resolution for conflicting interface defaults.

4. Are constructors inherited?

No. A subclass constructor invokes an accessible superclass constructor, but constructors are not inherited or overridden.

5. Are private superclass members inherited?

They form part of the superclass object’s implementation but are not directly accessible by the subclass. The superclass may expose controlled protected or public behavior.

6. What is the difference between extends and implements?

extends creates class inheritance or interface inheritance. A class uses implements to promise the contract of one or more interfaces.

7. What is the Liskov Substitution Principle?

Code expecting a parent type should work correctly with any subtype without broken promises, surprising restrictions, or invalid behavior.

8. Why is throwing UnsupportedOperationException from an inherited method often a warning sign?

It may mean the child cannot satisfy the parent’s contract, so the hierarchy does not represent a valid is-a relationship.

9. When should composition be preferred over inheritance?

Prefer composition when the relationship is has-a, behavior must be replaceable, or inheritance would be used only to reuse implementation.

10. Can an abstract class extend another class and implement interfaces?

Yes. It can extend one class and implement any number of interfaces.


4. 🔄 Polymorphism: One Contract, Many Behaviors

Polymorphism means “many forms.” In Java, the same operation can behave differently depending on the arguments selected at compile time or the actual receiver object used at runtime.

Java discussions usually divide polymorphism into:

  1. compile-time polymorphism through method overloading, and
  2. runtime polymorphism through method overriding and dynamic dispatch.

Notebook-style overloading versus overriding illustration

4.1 Compile-Time Polymorphism: Method Overloading

Method overloading means declaring methods with the same name but different parameter lists.

MealFlow may calculate a delivery fee using only distance, or distance plus a surge multiplier:

Java
class DeliveryFeeCalculator {

    long calculateFee(int distanceInKm) {
        return calculateFee(distanceInKm, 1.0);
    }

    long calculateFee(int distanceInKm, double surgeMultiplier) {
        long baseFeeInPaise = 2_000;
        long distanceFeeInPaise = distanceInKm * 500L;

        return Math.round(
                (baseFeeInPaise + distanceFeeInPaise)
                        * surgeMultiplier
        );
    }

    long calculateFee(String zoneCode) {
        if ("AIRPORT".equals(zoneCode)) {
            return 8_000;
        }
        return 3_000;
    }
}

The compiler selects an overload using the method name and the number, types, and order of arguments.

Java
DeliveryFeeCalculator calculator =
        new DeliveryFeeCalculator();

calculator.calculateFee(5);          // calculateFee(int)
calculator.calculateFee(5, 1.5);     // calculateFee(int, double)
calculator.calculateFee("AIRPORT");  // calculateFee(String)

Return type alone cannot create an overload:

Java
class InvalidCalculator {
    long calculateFee(int distance) {
        return 0;
    }

    /*
     * Does not compile: same method signature.
     *
     * double calculateFee(int distance) {
     *     return 0.0;
     * }
     */
}

Java operators are not ordinary methods, and Java does not allow developers to define custom operator overloads. The + operator simply has language-defined behavior for numbers and strings.

🧭 How Overload Selection Works

Overloading is decided from the compile-time argument types—not the runtime type of an argument object.

Java
class OrderPrinter {
    void print(Object value) {
        System.out.println("Object version");
    }

    void print(String value) {
        System.out.println("String version");
    }
}

class Main {
    public static void main(String[] args) {
        Object message = "Order confirmed";
        new OrderPrinter().print(message);
    }
}

Output:

Text
Object version

The variable is declared as Object, so the compiler selects print(Object).

4.2 Runtime Polymorphism: Method Overriding

Method overriding occurs when a subtype supplies its own implementation of an inherited instance method.

Java
interface NotificationChannel {
    void send(String destination, String message);
}

class EmailChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("Email sent to " + destination);
    }
}

class SmsChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("SMS sent to " + destination);
    }
}

class PushChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("Push sent to " + destination);
    }
}

One service can work with every implementation:

Java
class NotificationService {
    void notifyCustomer(
            NotificationChannel channel,
            String destination,
            String message
    ) {
        channel.send(destination, message);
    }
}

public class Main {
    public static void main(String[] args) {
        NotificationService service =
                new NotificationService();

        NotificationChannel channel = new EmailChannel();
        service.notifyCustomer(
                channel,
                "customer@example.com",
                "Your order is confirmed"
        );

        channel = new SmsChannel();
        service.notifyCustomer(
                channel,
                "+91-9999999999",
                "Your order is out for delivery"
        );
    }
}

The reference type is NotificationChannel, but the actual objects are EmailChannel and SmsChannel. At runtime, Java invokes the implementation belonging to the actual receiver object.

This is dynamic method dispatch.

Notebook-style runtime polymorphism in the MealFlow notification system

🚀 Why Polymorphism Improves Extensibility

Suppose we add a WhatsApp implementation:

Java
class WhatsAppChannel implements NotificationChannel {
    @Override
    public void send(String destination, String message) {
        System.out.println("WhatsApp message sent to " + destination);
    }
}

NotificationService does not change. It already depends on the abstraction.

This supports the Open/Closed Principle: extend behavior by adding a new implementation instead of repeatedly modifying stable client logic.

That benefit appears only when callers genuinely depend on the abstraction. If client code contains instanceof checks for every implementation, polymorphism has not been used effectively.

📌 Overriding Rules Worth Remembering

An overriding method:

  • must have the same name and parameter types after type erasure,
  • may return a covariant subtype—for example, an override can return Dog when the parent returns Animal, but cannot widen that return type to Object,
  • cannot reduce access visibility,
  • cannot declare broader checked exceptions—for example, an override may narrow IOException to FileNotFoundException, but cannot broaden it to Exception,
  • should use @Override so the compiler can verify the intent.

Also remember:

  • final instance methods cannot be overridden,
  • private methods are not overridden,
  • static methods are hidden, not overridden,
  • constructors are never overridden, and
  • fields are resolved by reference type rather than dynamically dispatched.

🧪 Two Override Edge Cases Interviewers Test

Covariant returns and narrower checked exceptions are both legal when they preserve the parent contract:

Java
import java.io.FileNotFoundException;
import java.io.IOException;

class PaymentResult {
}

class CardPaymentResult extends PaymentResult {
}

class PaymentProcessor {
    PaymentResult process() throws IOException {
        return new PaymentResult();
    }
}

class CardPaymentProcessor extends PaymentProcessor {
    @Override
    CardPaymentResult process() throws FileNotFoundException {
        return new CardPaymentResult();
    }
}

CardPaymentResult is a subtype of the original return type, and FileNotFoundException is narrower than IOException. A child cannot return an unrelated type or introduce a broader checked exception.

Overload resolution has its own traps. Widening is considered before boxing and varargs, and null can be ambiguous when unrelated reference overloads exist:

Java
class OverloadRules {
    void choose(long value) {
        System.out.println("primitive widening");
    }

    void choose(Integer value) {
        System.out.println("boxing");
    }

    void notify(String value) {
    }

    void notify(Integer value) {
    }

    void demo() {
        choose(1);       // chooses choose(long)
        // notify(null); // does not compile: String and Integer are ambiguous
    }
}

🧱 Fields Are Not Polymorphic

Java
class BaseChannel {
    String name = "Base";

    String name() {
        return "Base method";
    }
}

class SpecialChannel extends BaseChannel {
    String name = "Special";

    @Override
    String name() {
        return "Special method";
    }
}

class Main {
    public static void main(String[] args) {
        BaseChannel channel = new SpecialChannel();

        System.out.println(channel.name);   // Base
        System.out.println(channel.name()); // Special method
    }
}

The field uses the declared reference type. The overridden instance method uses the actual object type.

If you access the field through a SpecialChannel reference, Java selects the subclass field. If you access it through a BaseChannel reference, Java selects the superclass field even when that reference points to a SpecialChannel object. In the example above, the reference type is BaseChannel.

🌟 Benefits of Polymorphism

  • One client can work with several implementations.
  • New implementations can be introduced with fewer client changes.
  • Conditional logic is replaced by object-specific behavior.
  • Tests can supply controlled implementations.
  • Code becomes focused on contracts instead of concrete details.

⚖️ Trade-offs

  • Runtime behavior may require inspecting the actual implementation while debugging.
  • Too many layers can make control flow difficult to trace.
  • Weak abstractions can move complexity rather than reduce it.

Dynamic dispatch itself is normally not a practical performance problem. Modern JVMs can optimize and inline many call sites. A single System.nanoTime() measurement around one method call is not a valid benchmark; use JMH for serious Java microbenchmarking.

🎤 Polymorphism Interview Questions

1. What is polymorphism?

Polymorphism allows one operation or contract to have multiple forms of behavior, selected through overloading at compile time or overriding at runtime.

2. What is the difference between overloading and overriding?

Overloading uses the same method name with different parameter lists and is selected at compile time. Overriding replaces inherited instance behavior and is dispatched using the actual object type at runtime.

3. Can methods be overloaded by changing only the return type?

No. The compiler cannot choose an overload from return type alone.

4. Which type controls overloaded-method selection?

The compiler uses the compile-time types of the arguments and selects the most specific applicable overload.

5. Which type controls overridden-method dispatch?

The runtime class of the receiver object controls which overridden instance method executes.

6. Can an overriding method change the return type?

It may return a covariant subtype of the original return type.

7. Can an overriding method reduce visibility?

No. It can preserve or widen access, but it cannot make the inherited contract less accessible.

8. Are static methods polymorphic?

Static methods are selected by the reference or class at compile time and are hidden rather than overridden.

9. Are fields polymorphic?

No. Field access is resolved using the declared reference type.

10. Why should @Override be used?

It lets the compiler detect signature mistakes and clearly communicates the developer’s intent.

11. How does polymorphism support the Open/Closed Principle?

Clients can depend on a stable abstraction while new implementations are added without modifying the client flow.

12. Is runtime polymorphism slow?

It has dispatch mechanics, but the JVM often optimizes them. Design clarity normally matters far more, and performance claims should be verified with a proper benchmark.


Part II — Access Control and Object Relationships

5. 🔐 Access Modifiers: Expose Only What the Design Needs

Access modifiers control where a type or member can be used.

They are not only compiler syntax. They help define the boundary of each object and package.

A useful design principle is:

Insight

Start with the narrowest access that works. Widen it only when another part of the design truly needs it.

Java provides four access levels for members:

  1. private
  2. package-private, when no modifier is written
  3. protected
  4. public

5.1 private: Inside the Owning Class

A private member is intended for the implementation of its declaring class.

Java
class FoodOrder {
    private OrderStatus status = OrderStatus.DRAFT;

    public void confirm() {
        validateBeforeConfirmation();
        status = OrderStatus.CONFIRMED;
    }

    private void validateBeforeConfirmation() {
        // Internal validation detail
    }
}

Callers can use confirm(), but they cannot directly invoke the internal validation helper or modify status.

Private methods are not overridden by subclasses.

5.2 Package-Private: Inside One Package

When no access modifier is written, the type or member has package-private access.

Java
package com.mealflow.order;

class OrderNumberGenerator {
    String nextNumber() {
        return "ORD-101";
    }
}

Both the class and its method are available to code in com.mealflow.order, but not to classes in other packages.

This is useful for internal helpers that support a feature without becoming part of the public API.

Package-private is an access level, not a Java keyword or explicit modifier.

5.3 protected: Package Access Plus Controlled Subclass Access

A protected member is accessible:

  • from any class in the same package, and
  • from subclass code in another package, subject to Java’s receiver rule.
Java
package com.mealflow.delivery.core;

public abstract class DeliveryPartner {
    protected int basePreparationMinutes() {
        return 5;
    }
}

A subclass in another package may use the inherited method:

Java
package com.mealflow.delivery.bike;

import com.mealflow.delivery.core.DeliveryPartner;

public class BikeDeliveryPartner extends DeliveryPartner {
    public int estimate(int distanceInKm) {
        return basePreparationMinutes() + distanceInKm * 4;
    }
}

But cross-package subclass access does not mean the subclass can call the protected method through any arbitrary superclass reference:

Java
public class BikeDeliveryPartner extends DeliveryPartner {

    void inspect(DeliveryPartner other) {
        /*
         * Does not compile across packages:
         * other.basePreparationMinutes();
         */
    }

    void inspectBike(BikeDeliveryPartner otherBike) {
        // Valid through a suitable subclass reference.
        otherBike.basePreparationMinutes();
    }
}

This protected-receiver rule is a favorite Java interview edge case.

Use protected carefully. Exposing mutable fields directly to subclasses creates strong coupling. Private state plus narrow protected operations is usually safer.

5.4 public: Part of the Exposed Contract

A public type or member can be used wherever its enclosing type, package, and module are accessible.

Java
package com.mealflow.payment.api;

public interface PaymentProcessor {
    PaymentReceipt pay(PaymentRequest request);
}

Public APIs are promises. Once other code depends on them, changing their meaning becomes expensive. Do not make a member public merely because it is convenient during development.

Rules for Top-Level and Nested Types

A top-level class or interface can be:

  • public, or
  • package-private.

It cannot be private or protected.

A nested type may use public, protected, package-private, or private because it belongs inside another type.

Access Rules During Overriding

An overriding method cannot reduce visibility:

Java
class BaseNotifier {
    protected void send() {
    }
}

class EmailNotifier extends BaseNotifier {
    @Override
    public void send() { // Widening access is legal.
    }
}

Changing the override to private or package-private would not compile.

🔐 Access Control Is Not Authorization

Java access modifiers protect program structure at the language level. They do not decide whether a logged-in user may cancel someone else’s order.

Authorization belongs in the application and security design.

Notebook-style Java access modifiers illustration

🎤 Access-Modifier Interview Questions

1. What are Java’s four member-access levels?

They are private, package-private, protected, and public.

2. Is default an access modifier?

No. When no modifier is written, the member has package-private access. default is a different keyword used in contexts such as interface default methods and switch labels.

3. Can a top-level class be private or protected?

No. A top-level type can be public or package-private. Nested types can use all four access levels.

4. Is a protected member accessible to every subclass in every way?

No. A cross-package subclass may access it through inheritance and suitable subclass-typed receivers, not through any arbitrary superclass instance.

5. Can an overriding method reduce visibility?

No. It may preserve or widen the inherited method’s visibility.

6. Are private methods overridden?

No. A same-named method in a subclass is a separate declaration.

7. Why prefer the narrowest useful access?

It reduces coupling, protects implementation choices, and keeps the supported API smaller and easier to evolve.

8. Does public always mean accessible everywhere?

The enclosing type must also be accessible. In modular Java, the containing package may additionally need to be exported by its module.

9. Should fields normally be protected for subclass reuse?

Usually not. Protected mutable fields expose representation and tightly couple subclasses. Prefer private fields with controlled protected behavior.


6. 🔗 Class Relationships: How Objects Collaborate

OOP is not only about individual classes. An LLD becomes useful when we describe how objects relate to each other.

The most common relationships are:

  • inheritance,
  • realization,
  • association,
  • aggregation,
  • composition, and
  • dependency.

The code may look similar in some cases, so the real distinction often comes from meaning, ownership, and lifecycle.

6.1 Inheritance or Generalization: “Is-A”

Java
class BikeDeliveryPartner extends DeliveryPartner {
}

A BikeDeliveryPartner is a DeliveryPartner.

In UML, generalization uses a solid line with a hollow triangle pointing toward the parent.

6.2 Realization: “Implements This Contract”

Java
class UpiPaymentProcessor implements PaymentProcessor {
    @Override
    public PaymentReceipt pay(PaymentRequest request) {
        return new PaymentReceipt("UPI-TXN-303");
    }
}

The class realizes the interface’s contract.

When card and UPI processors implement pay(...) from PaymentProcessor, they turn the shared payment contract into channel-specific behavior. In UML, implementing an interface is realization. Extending an abstract class is generalization, even when the subclass implements an abstract method.

In UML, realization uses a dashed line with a hollow triangle pointing toward the interface.

Notebook-style UML realization relationship

6.3 Association: “Knows or Works With”

Association is a general, longer-lived relationship between independent objects.

Java
class FoodOrder {
    private DeliveryPartner assignedPartner;

    void assign(DeliveryPartner partner) {
        this.assignedPartner = partner;
    }
}

The order and delivery partner can exist independently, but the order may be associated with one partner.

In UML, association usually uses a solid line. Multiplicity may describe quantities such as one order to zero-or-one assigned partner.

Why This Is an Association

  • Independent lifecycles: A DeliveryPartner can exist while waiting for a job. A FoodOrder can exist while still in the kitchen or awaiting assignment.
  • Independent identity: Deleting an order does not delete the delivery-partner profile. If a partner leaves, the order can be reassigned.
  • Collaboration: The order stores a reference to its assigned partner to coordinate delivery. The assignment connects the objects without making either one own the other’s lifecycle.

Notebook-style UML association relationship

6.4 Aggregation: Weak Whole–Part Ownership

Aggregation is a specialized association in which one object groups other objects but does not own their independent lifecycle.

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

class DeliveryFleet {
    private final List<DeliveryPartner> partners =
            new ArrayList<>();

    void add(DeliveryPartner partner) {
        partners.add(partner);
    }
}

A delivery partner can exist before joining a fleet, leave the fleet, and join another one. Destroying a DeliveryFleet conceptually does not destroy the partners.

In UML, aggregation uses a hollow diamond at the whole—the DeliveryFleet side.

Understanding the Whole and Its Parts

The fleet groups delivery partners without controlling their independent lifecycle. Removing the fleet from the domain does not remove the partners from the domain.

In the example, a partner is created outside DeliveryFleet and passed to add(...). A partner may also be referenced elsewhere. Whether its Java object remains in memory depends on reachability, not on the aggregation label.

A department and its professors provide a useful analogy: if a department closes, the professors can join another department. The hollow diamond identifies the whole in the UML model.

Notebook-style UML aggregation relationship

6.5 Composition: Strong Whole–Part Ownership

Composition represents stronger ownership. The part belongs to the whole’s lifecycle and normally has no meaningful independent identity in that model.

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

class FoodOrder {
    private final List<OrderLine> lines = new ArrayList<>();

    void addItem(
            String itemName,
            int quantity,
            long unitPriceInPaise
    ) {
        lines.add(
                new OrderLine(itemName, quantity, unitPriceInPaise)
        );
    }
}

In this design, order lines are created and controlled through the order. If the order disappears from the domain, those lines have no separate business lifecycle.

In UML, composition uses a filled diamond at the whole—the FoodOrder side.

Java’s garbage collector does not enforce UML composition. Composition is a semantic ownership decision expressed by the design.

Understanding Strong Ownership

Within this domain model, an order line belongs to its order and has no separate business lifecycle. Removing the order removes those lines from the model; canceling an order may still retain them for history or auditing.

Here, FoodOrder.addItem(...) creates an OrderLine using new and controls its addition to the order. That expresses ownership, but it does not itself prevent other code from constructing an OrderLine; constructor visibility and the public API determine that boundary. Domain ownership also does not guarantee immediate deletion from memory or storage.

A house and its rooms provide an analogy: the rooms are parts of that house rather than independently managed buildings. The filled diamond identifies the whole in UML.

Notebook-style UML composition relationship

6.6 Dependency: “Temporarily Uses”

A dependency is a weaker, often temporary relationship. One class uses another to complete an operation without storing it as long-lived state.

Java
interface RoutePlanner {
    int estimateMinutes(String pickup, String destination);
}

class DispatchService {
    int estimateDelivery(
            FoodOrder order,
            RoutePlanner routePlanner
    ) {
        return routePlanner.estimateMinutes(
                "Restaurant",
                "Customer"
        );
    }
}

DispatchService depends on RoutePlanner for this operation.

A dependency can appear through method or constructor parameters, local variables, returned types, static calls, or temporary method usage. It is not limited to method parameters.

In UML, dependency uses a dashed arrow toward the type being used.

Understanding Temporary Usage

For this example, the rule is: “I need you for this operation, but I do not store you as part of my state.” DispatchService receives a RoutePlanner in estimateDelivery(...), uses it, and stores no planner field.

A carpenter borrowing a screwdriver for a task is a useful analogy. The dashed UML arrow points toward the type being used. Dependency is a broad usage relationship; the temporary parameter pattern shown here is one common form of it.

Notebook-style UML dependency relationship

Notebook-style class relationships cheat sheet

🧭 Association, Aggregation, or Composition?

Ask these questions:

  1. Can both objects exist independently?
  2. Does one object merely know or collaborate with the other?
  3. Does one group the other without owning its lifecycle?
  4. Does the part have a meaningful lifecycle outside the whole?
  5. Who creates, replaces, and removes the part?

Do not decide only by looking for a field. The same field shape can represent different semantics in different domains.

For example, a restaurant may aggregate independently existing chefs, while an order may compose order-line entries created only for that order.

📝 Do We Need UML in an LLD Interview?

You do not need to spend half the interview drawing perfect notation. A small class sketch can still help communicate:

  • the important types,
  • ownership,
  • multiplicity,
  • dependency direction, and
  • where polymorphism occurs.

Sketch enough to align with the interviewer, then move into responsibilities and code.

🎤 Class-Relationship Interview Questions

1. What is the difference between inheritance and association?

Inheritance represents an is-a relationship. Association represents objects that know or work with each other while remaining distinct.

2. What is the difference between aggregation and composition?

Aggregation groups independently living parts. Composition expresses strong ownership in which the part belongs to the whole’s lifecycle in that domain.

3. Does a field automatically mean composition?

No. A field only shows that one object stores a reference. Domain ownership and lifecycle determine whether the relationship is association, aggregation, or composition.

4. Does Java garbage collection enforce composition?

No. Composition is a design meaning. Garbage collection reclaims unreachable objects and does not understand UML ownership.

5. What is realization?

Realization is the relationship in which a class implements an interface contract.

6. What is a dependency?

It is a weaker usage relationship in which one type relies on another to perform some work, often without long-term ownership.

7. Is constructor injection a dependency?

Yes. The receiving class depends on the constructor parameter’s type, even if it stores that collaborator afterward.

8. Can two classes have both association and dependency?

Relationship labels describe the chosen model and usage. A long-lived stored collaborator is generally modeled as an association, while temporary usage is shown as a dependency.

9. Why is multiplicity useful?

It communicates how many objects may participate, such as one order containing one-or-more order lines or an order having zero-or-one assigned delivery partner.


Part III — Type-Safe Reuse with Generics and Wildcards

Generics and wildcards are not part of the four OOP pillars. They are Java type-system features that help us build reusable, type-safe abstractions.

They were introduced in Java 5 and are essential when designing collections, repositories, results, events, and framework APIs.

7. 📦 Generics: Reuse Code Without Losing Type Safety

Suppose MealFlow stores orders and restaurants in repositories.

Without generics, we might return Object and force callers to cast:

Java
interface UnsafeRepository {
    Object findById(String id);
    void save(Object value);
}

The compiler cannot prevent this mistake:

Java
UnsafeRepository repository = null;

// Compiles, but may fail at runtime.
Restaurant restaurant =
        (Restaurant) repository.findById("ORD-101");

Generics let the type relationship become part of the API.

🗃️ A Generic Repository

Java
import java.util.Optional;

interface Repository<T, ID> {
    Optional<T> findById(ID id);
    void save(T entity);
}

final class OrderId {
    private final String value;

    OrderId(String value) {
        this.value = value;
    }

    String value() {
        return value;
    }
}

interface OrderRepository
        extends Repository<FoodOrder, OrderId> {
}

Here:

  • T represents the entity type.
  • ID represents the identifier type.
  • OrderRepository fixes those parameters as FoodOrder and OrderId.
  • Callers receive an Optional<FoodOrder>, not an untyped Object.

If someone tries to save a restaurant through OrderRepository, the compiler rejects it.

🧱 Generic Classes

A class may declare one or more type parameters:

Java
final class OperationResult<T> {
    private final T value;
    private final String error;

    private OperationResult(T value, String error) {
        this.value = value;
        this.error = error;
    }

    static <T> OperationResult<T> success(T value) {
        return new OperationResult<>(value, null);
    }

    static <T> OperationResult<T> failure(String error) {
        return new OperationResult<>(null, error);
    }

    T value() {
        return value;
    }

    boolean isSuccessful() {
        return error == null;
    }
}
Java
OperationResult<PaymentReceipt> paymentResult =
        OperationResult.success(
                new PaymentReceipt("TXN-404")
        );

The diamond operator <>, introduced in Java 7, allows the compiler to infer the constructor’s type arguments.

🛠️ Generic Methods

A method may declare its own type parameter even when its class is not generic.

The type parameter appears before the return type:

Java
import java.util.List;
import java.util.Optional;

class CollectionUtils {
    static <T> Optional<T> first(List<T> values) {
        if (values.isEmpty()) {
            return Optional.empty();
        }
        return Optional.ofNullable(values.get(0));
    }
}

The relationship is preserved:

Java
List<String> orderIds = List.of("ORD-101", "ORD-102");
Optional<String> firstOrderId = CollectionUtils.first(orderIds);

📏 Bounded Type Parameters

Sometimes a generic type must provide a capability.

Java
interface Identifiable<ID> {
    ID id();
}

class EntityPrinter {
    static <ID, T extends Identifiable<ID>> void printId(T entity) {
        System.out.println(entity.id());
    }
}

T is not completely unrestricted. It must implement Identifiable<ID>.

Multiple bounds are also possible:

Java
static <T extends Comparable<T> & Identifiable<String>>
T chooseFirst(T first, T second) {
    return first.compareTo(second) <= 0 ? first : second;
}

When a class bound is present, it must appear before interface bounds.

🔗 Generics Work with Reference Types

This is illegal:

Java
// OperationResult<int> result; // Does not compile

Use the wrapper type:

Java
OperationResult<Integer> result = OperationResult.success(42);

Autoboxing converts between int and Integer where applicable.

Arrays of primitives are objects, so this is legal:

Java
OperationResult<int[]> values =
        OperationResult.success(new int[]{1, 2, 3});

🧷 Generics Are Invariant

Even though Integer extends Number, this is not allowed:

Java
List<Integer> integers = List.of(1, 2, 3);

// Does not compile:
// List<Number> numbers = integers;

Why? If it were allowed, someone could add a Double through numbers, corrupting a list that promises to contain only Integer values.

Wildcards solve controlled versions of this flexibility, which we will see next.

🚫 Avoid Raw Types

Java
// Raw type: generic information is discarded.
OperationResult rawResult = OperationResult.success("confirmed");

Raw types exist mainly for backward compatibility with pre-Java-5 code. They weaken compile-time safety and can produce unchecked warnings or runtime ClassCastException failures.

Prefer:

Java
OperationResult<String> result =
        OperationResult.success("confirmed");

🧹 Type Erasure

Java implements most generics through type erasure. The compiler verifies generic types and then erases much of that type information in generated bytecode.

This explains several limitations:

  • no new T(),
  • no T.class,
  • no new T[10],
  • no instanceof List<String>,
  • no static field using a class-level type parameter, and
  • no separate overloads whose signatures become identical after erasure.

This does compile:

Java
if (value instanceof List<?>) {
    System.out.println("The value is some kind of List");
}

List<?> is reifiable enough for this runtime check; List<String> is not.

💥 Heap Pollution: A Concrete Failure Mode

Heap pollution happens when a parameterized reference points at data of the wrong runtime type. Raw types and unchecked casts are common causes:

Java
import java.util.List;

class HeapPollutionDemo {
    @SuppressWarnings({"unchecked", "rawtypes"})
    static void corrupt() {
        List<String>[] values = (List<String>[]) new List[]{
                List.of("confirmed")
        };

        Object[] asObjects = values;
        asObjects[0] = List.of(42); // the array cannot see String at runtime

        String status = values[0].get(0); // ClassCastException here
        System.out.println(status);
    }
}

The compiler warning is valuable information, not noise. Prefer typed collections, avoid raw types, and use @SafeVarargs only when a generic varargs method truly cannot corrupt its array.

🎯 Why Generics Matter in LLD

Generics help express design relationships precisely:

  • a repository stores one entity type,
  • an identifier belongs to a particular entity,
  • an operation result wraps one known payload type,
  • an event handler handles one event family, and
  • a cache maps a known key type to a known value type.

They reduce duplicated infrastructure without turning everything into Object.

Notebook-style Java generics illustration

🎤 Generics Interview Questions

1. What problem do generics solve?

They let classes, interfaces, and methods reuse logic across types while preserving compile-time type relationships and reducing casts.

2. Where is <T> placed in a generic method?

Before the return type:

Java
static <T> T identity(T value) {
    return value;
}

3. Can generics use primitive type arguments?

No. Use reference wrappers such as Integer, Long, and Boolean. Primitive arrays are still reference types.

4. Why is List<Integer> not a subtype of List<Number>?

Generics are invariant. Allowing the assignment would make it possible to add another Number subtype, such as Double, into a list of integers.

5. What is a raw type?

It is a use of a generic declaration without type arguments, such as List instead of List<String>. It weakens safety and should normally be avoided.

6. What is type erasure?

It is the compiler strategy that checks generic types at compile time and removes much of their concrete type information from runtime representation.

7. Why can we not write new T()?

The runtime normally does not know the concrete erased type or which constructor should be invoked. A factory or Supplier<T> can be passed when creation is required.

8. Can a static field use a class’s type parameter?

No. The static field belongs to the class itself, while the type parameter belongs to each parameterized use of that class.

9. What is a bounded type parameter?

It restricts the types that may be supplied, such as <T extends Comparable<T>>.

10. What is heap pollution?

Heap pollution occurs when a variable of a parameterized type refers to data that does not satisfy its declared type, often through raw types, unsafe casts, or generic varargs misuse.


8. 🌪️ Wildcards: Flexible Relationships Between Generic Types

A wildcard represents an unknown type argument.

Java
List<?> values

This means “a list of some specific type, but this code does not know which type.” It does not mean the list contains arbitrary mixed values.

Java provides three wildcard forms:

  1. unbounded wildcard: <?>
  2. upper-bounded wildcard: <? extends T>
  3. lower-bounded wildcard: <? super T>

8.1 Unbounded Wildcard: <?>

Use an unbounded wildcard when the element type is irrelevant to the operation.

Java
static void printValues(List<?> values) {
    for (Object value : values) {
        System.out.println(value);
    }
}

The method can accept List<String>, List<Integer>, or List<FoodOrder>.

It can safely read each element as Object.

List<?> is often described as read-only, but that is shorthand rather than a complete rule. Depending on the collection, code may still remove elements, clear the list, or add null. It cannot safely add an arbitrary non-null object because the unknown element type may reject it.

8.2 Upper-Bounded Wildcard: <? extends T>

An upper-bounded wildcard accepts T or a subtype of T.

Java
abstract class OrderEvent {
    private final String orderId;

    OrderEvent(String orderId) {
        this.orderId = orderId;
    }

    String orderId() {
        return orderId;
    }
}

class OrderConfirmed extends OrderEvent {
    OrderConfirmed(String orderId) {
        super(orderId);
    }
}

class OrderDelivered extends OrderEvent {
    OrderDelivered(String orderId) {
        super(orderId);
    }
}

static void printOrderIds(
        List<? extends OrderEvent> events
) {
    for (OrderEvent event : events) {
        System.out.println(event.orderId());
    }
}

The method may receive List<OrderConfirmed>, List<OrderDelivered>, or List<OrderEvent>.

It can safely read values as OrderEvent, but it cannot safely add a non-null OrderEvent. The actual list might accept only OrderConfirmed.

Notebook-style upper-bounded wildcard explanation

8.3 Lower-Bounded Wildcard: <? super T>

A lower-bounded wildcard accepts T or one of its supertypes.

Java
static void addConfirmationEvent(
        List<? super OrderConfirmed> destination,
        String orderId
) {
    destination.add(new OrderConfirmed(orderId));
}

The destination may be:

  • List<OrderConfirmed>,
  • List<OrderEvent>, or
  • List<Object>.

The method can safely add an OrderConfirmed. When reading, however, the only universally safe type is Object.

Notebook-style lower-bounded wildcard explanation

📦 PECS: Producer Extends, Consumer Super

Joshua Bloch’s memorable rule is:

Insight

Producer Extends, Consumer Super.

  • If a structure produces values for your method to read, use ? extends T.
  • If a structure consumes values your method writes, use ? super T.

A copy operation uses both:

Java
static <T> void copy(
        List<? extends T> source,
        List<? super T> destination
) {
    for (T value : source) {
        destination.add(value);
    }
}

The source produces T; the destination consumes T.

Notebook-style PECS wildcard illustration

🤔 When to Use a Generic Type Parameter vs. a Wildcard

A type parameter and a wildcard are both parts of Java generics, but they express different intentions:

  • <T> names a type so the API can preserve a relationship.
  • ? says that one definite type exists, but this method does not need to name it.

Use a named type parameter when:

  • an input type determines the return type,
  • two or more parameters must share a type relationship,
  • a method must move values safely between related inputs, or
  • the algorithm needs a bound such as <T extends Comparable<T>>.

For example, the input element type determines the return type here:

Java
static <T> T first(List<T> values) {
    if (values.isEmpty()) {
        throw new IllegalArgumentException("values must not be empty");
    }
    return values.get(0);
}

Use a wildcard when:

  • the exact element type is irrelevant,
  • the method only performs type-independent work,
  • an input should accept a family of related generic types, or
  • the method needs one-way producer or consumer behavior.

The exact element type does not need a name here:

Java
static int sizeOf(List<?> values) {
    return values.size();
}

Use this decision path in an interview:

  1. If the API requires one exact element type, use a concrete type such as List<OrderEvent>.
  2. If the same unknown type must connect multiple parameters or a return value, name it with <T>.
  3. If the type is irrelevant and only Object-level behavior is needed, use <?>.
  4. If the input produces values that you read as T, use <? extends T>.
  5. If the destination consumes values that you add as T, use <? super T>.

If the method must both read and write the same exact element type, prefer List<T> rather than forcing a wildcard.

The deciding question is simple: does this API need to preserve a type relationship, or only accept a flexible range of types?

Avoid wildcard return types in most public APIs because callers then have to reason about an unknown captured type. Return a concrete generic relationship when possible.

Notebook-style decision guide for type parameters and wildcards

🪄 Wildcard Capture

Sometimes a helper method is needed so the compiler can give a wildcard’s unknown type a temporary name.

Java
static void reverse(List<?> values) {
    reverseCaptured(values);
}

private static <T> void reverseCaptured(List<T> values) {
    java.util.Collections.reverse(values);
}

This technique is called wildcard capture.

🎤 Wildcard Interview Questions

1. What does List<?> mean?

It is a list of one unknown element type. Elements can safely be read as Object, but arbitrary non-null values cannot be added.

2. What does ? extends Number mean?

It represents one unknown type that is Number or a subtype of Number, such as Integer or Double.

3. Why can we not add an Integer to List<? extends Number>?

The actual list might be a List<Double>. The compiler does not know the captured subtype, so adding an integer would be unsafe.

4. What does ? super Integer mean?

It represents one unknown type that is Integer or a supertype, such as Number or Object.

5. What can we read from List<? super Integer>?

Only Object is universally safe because the actual list might be parameterized with any supertype of Integer.

6. What is PECS?

Producer Extends, Consumer Super: use extends when reading values and super when writing values.

7. Is List<?> immutable?

No. It restricts type-safe additions, but mutating operations such as removal or clearing may still be allowed by the collection implementation.

8. When should a type parameter be used instead of a wildcard?

Use a type parameter when several inputs or a return type must share the same named type relationship.

9. Can a type parameter have a lower bound such as <T super Integer>?

No. Java supports upper bounds for named type parameters. Lower bounds are available for wildcards through ? super T.

10. What is wildcard capture?

It is the compiler’s treatment of an unknown wildcard as one specific hidden type. A generic helper method can sometimes name that captured relationship and perform an operation safely.


Part IV — Bringing the Design Together

9. 🧩 How the Concepts Work Together

The concepts become useful when they cooperate rather than appearing as isolated definitions.

Consider one MealFlow checkout request:

  1. FoodOrder encapsulates its items, total, and legal state transitions.
  2. CheckoutService depends on the PaymentProcessor abstraction.
  3. CardPaymentProcessor and UpiPaymentProcessor realize that contract.
  4. Runtime polymorphism selects the correct pay() implementation.
  5. A BikeDeliveryPartner may use valid inheritance from DeliveryPartner.
  6. The order composes its order lines and is associated with an assigned partner.
  7. Access modifiers keep internal transition logic hidden.
  8. Repository<FoodOrder, OrderId> provides type-safe reusable infrastructure through generics.
  9. Wildcards make collection APIs flexible without giving up safety.

The result is not “more OOP.” It is a set of objects whose responsibilities and boundaries match the business problem.

🔗 A Small Integrated Flow

Java
class OrderApplicationService {
    private final OrderRepository orderRepository;
    private final PaymentProcessor paymentProcessor;
    private final NotificationChannel notificationChannel;

    OrderApplicationService(
            OrderRepository orderRepository,
            PaymentProcessor paymentProcessor,
            NotificationChannel notificationChannel
    ) {
        this.orderRepository = orderRepository;
        this.paymentProcessor = paymentProcessor;
        this.notificationChannel = notificationChannel;
    }

    void confirmAndPay(
            FoodOrder order,
            String customerDestination
    ) {
        // Encapsulated domain operation
        order.confirm();

        // Abstraction + runtime polymorphism
        PaymentReceipt receipt = paymentProcessor.pay(
                new PaymentRequest(
                        "current-order",
                        order.totalInPaise()
                )
        );

        // Generic repository contract
        orderRepository.save(order);

        // Another polymorphic collaboration
        notificationChannel.send(
                customerDestination,
                "Payment completed: " + receipt.transactionId()
        );
    }
}

This service coordinates the use case but does not take ownership of every responsibility:

  • the order protects its rules,
  • the payment processor handles payment behavior,
  • the repository handles persistence, and
  • the notification channel handles communication.

That separation produces high cohesion and manageable coupling.

Notebook-style integrated MealFlow OOP design


10. 🪜 A Step-by-Step OOP Framework for LLD Interviews

When an interviewer gives you an LLD problem, use this order of thinking.

1️⃣ Step 1: Identify the Important Domain Objects

Ask which nouns have identity, state, lifecycle, or business rules.

For MealFlow, likely candidates include:

  • FoodOrder,
  • Restaurant,
  • Customer,
  • DeliveryPartner, and
  • PaymentReceipt.

Do not automatically turn every noun into a class. A concept deserves a type when it helps express the model.

2️⃣ Step 2: Assign One Clear Responsibility

Ask what each object should know and what it should do.

An order owns order rules. A payment processor performs payment. A notification channel sends a message.

Avoid one “manager” class that performs everything.

3️⃣ Step 3: Protect Invariants

Keep mutable state private. Expose domain operations that make illegal state difficult or impossible.

4️⃣ Step 4: Find the Real Points of Variation

Payment provider and notification channel vary naturally. Those are strong candidates for interfaces.

Do not add an interface merely because a class exists.

5️⃣ Step 5: Choose Relationships Deliberately

Ask:

  • Is this truly is-a?
  • Is it has-a?
  • Who owns the lifecycle?
  • Is the collaboration temporary or long-lived?
  • Could composition be safer than inheritance?

6️⃣ Step 6: Keep Access Narrow

Make implementation details private or package-private. Expose only the behavior that callers need.

7️⃣ Step 7: Use Generics for Repeating Type-Safe Infrastructure

Repositories, result wrappers, caches, event handlers, and paginated responses are common candidates.

Do not make domain classes generic unless the domain genuinely contains a type variation.

8️⃣ Step 8: Test the Design with Change

Ask how the design reacts when:

  • WhatsApp notifications are introduced,
  • cash-on-delivery is added,
  • order cancellation rules change,
  • delivery partners gain new capabilities, or
  • a second repository implementation appears.

A good design localizes each change instead of spreading if/else modifications across the codebase.

9️⃣ Step 9: Explain Trade-offs

Interviewers are rarely looking for one magical class diagram. Explain why you chose an interface, why composition is appropriate, and what complexity you intentionally avoided.

Notebook-style Java LLD interview framework


11. 🧠 How the OOP Concepts Connect to SOLID

You do not need to force SOLID into every answer, but the connection is useful.

🎯 Single Responsibility Principle

Encapsulation works best when a class protects one cohesive responsibility. FoodOrder handles order rules; it should not send emails or call payment gateways.

🚪 Open/Closed Principle

Abstraction and polymorphism let MealFlow add another NotificationChannel or PaymentProcessor without repeatedly editing stable client logic.

🔁 Liskov Substitution Principle

Inheritance is valid only when each subtype can honor its parent contract without surprising failures or weaker guarantees.

🧩 Interface Segregation Principle

Small capability interfaces such as Trackable and Motorized prevent classes from implementing irrelevant methods.

🔌 Dependency Inversion Principle

High-level use cases such as checkout depend on PaymentProcessor, not directly on a particular payment provider.

SOLID does not replace OOP. It helps us judge whether our object-oriented boundaries are healthy.


12. ⚠️ Common OOP and LLD Mistakes

1. Treating Getters and Setters as Complete Encapsulation

Exposing every field through setters can turn a class into an unprotected data bag.

2. Creating Interfaces for Every Class

An interface with no useful variation, boundary, or test seam adds ceremony rather than flexibility.

3. Using Inheritance Only for Code Reuse

If the subtype is not truly substitutable for the parent, use composition or a smaller capability interface.

4. Building Deep Hierarchies

Deep inheritance spreads knowledge across many levels and makes behavior difficult to trace.

5. Forcing Irrelevant Methods on Implementations

If implementations throw UnsupportedOperationException, revisit the abstraction and apply interface segregation.

6. Confusing Overloading with Overriding

Overloading is selected from compile-time signatures. Overriding is selected from the actual receiver at runtime.

7. Believing Fields Are Dynamically Dispatched

Overridden instance methods are polymorphic; fields are selected using the declared reference type.

8. Misunderstanding protected

Cross-package subclass access follows the protected-receiver rule. Extending a class does not make every superclass instance’s protected members freely accessible.

9. Calling Every Stored Reference Composition

Ownership and lifecycle determine composition—not the presence of a field.

10. Ignoring Aggregation and Composition

These relationships communicate important lifecycle decisions even though Java does not enforce their UML semantics.

11. Using Raw Collections

Raw types discard generic safety and move failures toward runtime.

12. Assuming List<Child> Is a List<Parent>

Java generics are invariant. Use an appropriate wildcard when controlled variance is required.

13. Repeating “Wildcards Are Read-Only” as an Absolute Rule

Wildcards restrict type-safe insertion; they do not make the collection immutable.

14. Optimizing Dynamic Dispatch Without Evidence

Do not damage the design to avoid theoretical method-dispatch costs. Measure real performance with an appropriate benchmark.

15. Designing for Imaginary Future Requirements

Extensibility is valuable, but speculative abstractions make today’s design harder. Apply KISS and YAGNI.


13. 🧪 Practice Challenge: Design MealFlow Yourself

Try designing this use case without copying the article’s code.

Requirements

  • A customer creates an order containing one or more order lines.
  • The order moves through valid status transitions.
  • Payment may happen through card, UPI, or cash on delivery.
  • A delivery partner may travel by bike, car, or on foot.
  • Some partners are trackable; some are motorized.
  • Notifications may be delivered through email, SMS, or push.
  • Orders must be stored in a repository.
  • The dispatch service temporarily uses a route planner.

Questions to Answer

  1. Which state belongs inside FoodOrder?
  2. Which operations protect its invariants?
  3. Which types should be interfaces?
  4. Is DeliveryPartner better as an interface or abstract class in your version?
  5. Which relationships are composition, aggregation, association, and dependency?
  6. Which members should be public, protected, package-private, or private?
  7. Where does runtime polymorphism occur?
  8. Can a generic repository serve several aggregate types safely?
  9. Where would ? extends T or ? super T improve an API?
  10. How would you add WhatsApp notifications without editing the checkout flow?

👀 What an Interviewer Will Look For

  • clear responsibilities,
  • valid state transitions,
  • meaningful abstractions,
  • shallow and justified inheritance,
  • correct ownership,
  • dependency direction,
  • safe access boundaries,
  • type-safe reusable code, and
  • an explanation of trade-offs.

14. ⚡ Quick Revision

  • Encapsulation combines state and behavior behind a controlled API.
  • Private fields alone do not guarantee good encapsulation.
  • Domain operations are often safer than generic setters.
  • Abstraction exposes what a capability does while hiding how it works.
  • Abstract classes may contain constructors, state, abstract methods, and concrete methods.
  • Interfaces define capabilities and can include default, static, and private methods.
  • Java interface fields are constants, not per-object mutable state.
  • Conflicting unrelated interface defaults require explicit resolution.
  • A default method can be re-abstracted.
  • Inheritance should express a genuine is-a relationship.
  • Java classes have one direct superclass but may implement many interfaces.
  • A subtype should honor the parent contract.
  • Composition is often safer when behavior must vary independently.
  • Overloading is selected at compile time using argument types.
  • Overriding uses the actual receiver object at runtime.
  • Return type alone cannot overload a method.
  • Static methods are hidden, private methods are separate, and fields are not dynamically dispatched.
  • Package-private means no access modifier is written.
  • Top-level types can be public or package-private.
  • Protected cross-package access follows a special receiver rule.
  • An override cannot reduce visibility.
  • Inheritance means is-a; realization means implements a contract.
  • Association is a general object relationship.
  • Aggregation expresses weak whole–part ownership.
  • Composition expresses strong domain ownership and lifecycle dependency.
  • Dependency represents usage rather than ownership.
  • UML meaning comes from the domain, not only from code shape.
  • Generics provide reusable compile-time type safety.
  • Generic type arguments must be reference types.
  • Generic types are invariant.
  • Raw types should normally be avoided.
  • Type erasure creates important runtime limitations.
  • <?> represents one unknown type.
  • ? extends T is useful for producers.
  • ? super T is useful for consumers.
  • PECS means Producer Extends, Consumer Super.
  • Use a named type parameter when a type relationship must be preserved.
  • Good OOP is about clear responsibilities and boundaries—not the number of classes.

🏁 Final Takeaway

The four OOP pillars are not four independent definitions to memorize.

They form one design language:

  • Encapsulation protects an object’s rules.
  • Abstraction exposes a useful contract.
  • Inheritance models a valid specialization.
  • Polymorphism lets implementations vary behind that contract.

Access modifiers define the boundaries. Class relationships explain how objects collaborate. Generics and wildcards let reusable APIs remain type-safe.

When these ideas are used with purpose, an LLD becomes easier to explain, extend, test, and maintain.

The goal is not to make the design look complicated. The goal is to make the business rules clear in code. 🚀

Notebook-style OOP final recap

Continue learning

Back to LLD →

Clarity check

Did this explanation help?

Your quick rating stays in this browser. Use the email option if you want the feedback to reach Rahul.