LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · PILLAR · 3 OF 48

Abstraction in Java: Hide the How, Expose the What, With Examples

What abstraction means in object-oriented design, shown with parcel couriers: a checkout that knows only a Courier contract, interfaces and abstract types as promises, swapping and faking implementations, keeping each method at one level of abstraction, leaky abstractions, how abstraction differs from encapsulation, and when not to add one, with Java 17 code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 172 lines, with a small main() demo. Save it as AbstractionDemo.java, then run javac AbstractionDemo.java && java AbstractionDemo.

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

/**
 * Abstraction with parcel couriers.
 * Part 1: TangledCheckout knows every courier's fee rules and id format.
 * Part 2: Checkout depends only on the Courier contract (WHAT), and each
 *         courier keeps its own details (HOW) private.
 */
public class AbstractionDemo {

    public static void main(String[] args) {
        Parcel toPune = new Parcel(2.0, "411001");
        Parcel toHills = new Parcel(2.0, "190001");

        // ---------- Part 1: the problem ----------
        TangledCheckout tangled = new TangledCheckout();
        System.out.println("Tangled: " + tangled.send(toPune, "road"));

        // ---------- Part 2: the clean version ----------
        Checkout checkout = new Checkout(List.of(new RoadCourier(), new AirCourier()));
        System.out.println("Pune parcel  -> " + checkout.send(toPune));
        System.out.println("Hills parcel -> " + checkout.send(toHills));

        // Same Checkout, a fake courier: no fee tables, nothing real shipped.
        FakeCourier fake = new FakeCourier();
        Checkout underTest = new Checkout(List.of(fake));
        underTest.send(toPune);
        System.out.println("Fake recorded " + fake.shipped.size() + " parcel(s)");
    }
}

// ---------- Part 1: the problem ----------

/** Knows HOW every courier works. Every new courier or fee change edits this class. */
class TangledCheckout {
    private int seq;

    String send(Parcel p, String mode) {
        if (mode.equals("road")) {
            long fee = 40 + Math.round(p.kg() * 12);
            if (p.pincode().startsWith("19")) {
                fee += 60;
            }
            return "RD-" + p.pincode().substring(0, 3) + "-" + (++seq) + " for " + fee;
        } else if (mode.equals("air")) {
            long fee = 150 + Math.round(p.kg() * 55) + 20;
            return "AIR" + (++seq) + " for " + fee;
        }
        throw new IllegalArgumentException("unknown mode " + mode);
    }
}

// ---------- Part 2: the clean version ----------

record Parcel(double kg, String pincode) {
    Parcel {
        if (kg <= 0) {
            throw new IllegalArgumentException("weight must be positive");
        }
    }
}

/** The contract: WHAT a courier does. No formulas, no hubs, no flights. */
interface Courier {
    String name();

    long quote(Parcel p);   // price in rupees

    String ship(Parcel p);  // returns a tracking id
}

/** HOW the road courier works stays inside this class. */
class RoadCourier implements Courier {
    private int seq;

    @Override
    public String name() {
        return "road";
    }

    @Override
    public long quote(Parcel p) {
        long fee = 40 + Math.round(p.kg() * 12);
        return isHillArea(p) ? fee + 60 : fee;
    }

    @Override
    public String ship(Parcel p) {
        return "RD-" + hubFor(p) + "-" + (++seq);
    }

    private boolean isHillArea(Parcel p) {
        return p.pincode().startsWith("19");
    }

    private String hubFor(Parcel p) {
        return p.pincode().startsWith("41") ? "PUN" : "HUB" + p.pincode().charAt(0);
    }
}

/** HOW the air courier works stays inside this class. Hill areas are cheap by air here. */
class AirCourier implements Courier {
    private int seq;
    private final long fuelFee = 20;

    @Override
    public String name() {
        return "air";
    }

    @Override
    public long quote(Parcel p) {
        long fee = 150 + Math.round(p.kg() * 55) + fuelFee;
        return p.pincode().startsWith("19") ? fee / 3 : fee;
    }

    @Override
    public String ship(Parcel p) {
        return "AIR-" + flightSlot() + "-" + (++seq);
    }

    private String flightSlot() {
        return "F" + (seq % 3 + 1);
    }
}

/** A test double. It works only because Checkout depends on the contract. */
class FakeCourier implements Courier {
    final List<Parcel> shipped = new ArrayList<>();

    @Override
    public String name() {
        return "fake";
    }

    @Override
    public long quote(Parcel p) {
        return 10;
    }

    @Override
    public String ship(Parcel p) {
        shipped.add(p);
        return "FAKE-" + shipped.size();
    }
}

/** The caller: one level of abstraction, no courier details at all. */
class Checkout {
    private final List<Courier> couriers;

    Checkout(List<Courier> couriers) {
        if (couriers.isEmpty()) {
            throw new IllegalArgumentException("need at least one courier");
        }
        this.couriers = List.copyOf(couriers);
    }

    String send(Parcel p) {
        Courier best = cheapest(p);
        String trackingId = best.ship(p);
        return best.name() + " for " + best.quote(p) + " rupees, tracking " + trackingId;
    }

    private Courier cheapest(Parcel p) {
        return couriers.stream()
                .min(Comparator.comparingLong(c -> c.quote(p)))
                .orElseThrow();
    }
}

Notes

The problem

Here is a checkout that ships parcels. It knows the road courier's fee formula, its hill area surcharge and how it builds tracking ids. It also knows the air courier's fuel fee and flight slots. Adding a third courier means editing checkout again. Changing one fee rule means retesting all of checkout. And you cannot test checkout without the real courier logic running inside it.

A checkout that knows too much
if (mode.equals("road")) {
  double fee = 40 + kg * 12;
  if (pin.startsWith("19")) fee += 60;
  id = "RD-" + hubFor(pin) + "-" + seq++;
} else if (mode.equals("air")) {
  double fee = 150 + kg * 55 + fuel();
  id = "AIR" + flightSlot() + seq++;
}
// new courier: edit and retest checkout

The idea

Abstraction means giving callers a simple view of what something does and hiding how it does it. What does checkout really need from a courier? Only two things. How much will this parcel cost? And please ship it and give me a tracking id. Fee formulas, hubs, flight slots and fuel prices are details. Abstraction draws a line between those two questions and everything else.

In one sentence
  • abstraction: give callers a
  • simple view of WHAT an
  • object does and hide HOW
  • checkout needs two answers:
  • how much will it cost?
  • ship it, give me an id
  • everything else is detail

The contract

In Java we write the what as an interface. The Courier interface has three methods: a name, a quote for a parcel in rupees, and ship, which returns a tracking id. A parcel is a small record with its weight and pincode. Notice what is missing: no fee formula, no hub, no flight slot. The interface is a contract that any courier can sign, however it works inside.

interface Courier
interface Courier {
  String name();
  long quote(Parcel p);   // in rupees
  String ship(Parcel p);  // tracking id
}

record Parcel(double kg, String pincode)

no fields, no formulas, no hubs

The hidden how

Each courier implements the contract in its own way. Road courier keeps its base fee, its per kilo rate and its hill area surcharge private. Air courier has its own fuel fee and flight slots. These details now live in one class each. If the road courier changes its hill surcharge, only one class changes, and checkout does not even need to be recompiled.

class RoadCourier
class RoadCourier implements Courier {
  public long quote(Parcel p) {
    long fee = 40 + Math.round(p.kg() * 12);
    return isHill(p) ? fee + 60 : fee;
  }
  public String ship(Parcel p) {
    return "RD-" + hubFor(p) + "-" + ++seq;
  }
  private boolean isHill(Parcel p) {..}
}

The caller

Now checkout receives a list of couriers and only talks through the interface. To send a parcel, it asks each courier for a quote, picks the cheapest, and calls ship. The words road and air do not appear anywhere in checkout. A new courier is a new class plus one line where the list is built. Checkout itself never changes.

Checkout
Checkout(List<Courier> couriers) {..}

String send(Parcel p) {
  Courier best = cheapest(p);
  return best.ship(p);
}

// no "road", no "air", no formulas

Run-through

Trace one order. A two kilo parcel to Pune. Checkout asks the road courier for a quote and gets sixty four rupees. It asks the air courier and gets two hundred and eighty. It picks road and calls ship, and gets back a tracking id. Checkout made three calls through one interface and never learned how either courier works inside.

Testing

A big reward of abstraction is testing. Because checkout only knows the Courier interface, a test can hand it a fake courier that returns a fixed quote and simply records what it shipped. No network, no fee tables, and the test runs in milliseconds. If you cannot easily write a fake for something, that is a hint the abstraction is missing or leaking.

A fake for tests
class FakeCourier implements Courier {
  final List<Parcel> shipped = ..;
  public long quote(Parcel p) {
    return 10;
  }
  public String ship(Parcel p) {
    shipped.add(p);
    return "FAKE-" + shipped.size();
  }
}

Levels of abstraction

Abstraction also works inside a single method. A method should stay at one level of detail. If place order validates the cart, and then suddenly builds a SQL string by hand, the reader keeps jumping between business steps and low level plumbing. Keep the top method as a short story of steps, validate, reserve stock, send, notify, and push each detail down into its own method or class.

One level per method
// mixed levels: hard to read
placeOrder() {
  validate(cart);
  String sql = "INSERT INTO orders...";
  ...
}
// one level: reads like a story
placeOrder() {
  validate(cart); reserveStock(cart);
  String id = checkout.send(parcel);
  notifyBuyer(id); }

Abstract types

Java gives you two tools for abstraction. An interface describes only the contract, with optional default methods. An abstract class can describe the contract and also share some code and fields between implementations, but you cannot create one with new. Both let callers depend on what, not how. Lesson six compares them in detail, including how to choose between them.

Two tools
  • interface: only the contract
  • (plus optional defaults)
  • abstract class: contract plus
  • shared code and fields;
  • cannot be created with new
  • both let callers depend on
  • the what, not the how
  • lesson six compares them

vs encapsulation

People often mix up abstraction and encapsulation. Abstraction is a design decision about what callers should see: a courier can quote and ship. Encapsulation is the mechanism that keeps the rest out of reach: the fee fields are private and cannot be changed from outside. You choose the abstraction first, then use encapsulation to protect it. They work together, but they answer different questions.

Not the same thing
  • abstraction:
  • design-level choice of
  • WHAT callers see
  • (Courier: quote + ship)
  • encapsulation:
  • enforcing that the hidden
  • part cannot be touched
  • (private fee fields)
  • they work together

Leaky abstractions

An abstraction leaks when callers still need the hidden details to use it correctly. Signs include method names that describe the how, like ship via hub Pune, callers catching database errors from something that was supposed to hide the database, or callers checking which concrete class they really have. When you see a leak, fix the contract instead of adding more special cases in the callers.

Signs of a leak
  • • method names expose the
  • how: shipViaHubPune()
  • • callers catch SqlException
  • from a "repository"
  • • callers check
  • "if (c instanceof Air)"
  • • results mean different
  • things per implementation
  • fix: change the contract

When not to

Abstraction is not free. Every interface is one more file and one more jump when someone reads the code. Add one when there are several real implementations, when tests need a fake, or at a boundary with another system such as payments, email or a database. An interface with one implementation that will never change, added just in case, mostly adds noise.

Cost of abstraction
  • every interface is one more
  • file and one more jump when
  • reading code
  • good reasons:
  • several real implementations
  • a fake needed for tests
  • a boundary to another system
  • weak reason: "just in case"

In interviews

In design rounds, abstraction is how you show the design can grow. Find what varies and put it behind an interface named after its job. A payment method, a pricing policy for a parking lot, a notifier, a sink for a logger. Then the core classes depend only on those interfaces. Common mistakes are names that describe the how, and creating an interface for every class whether it varies or not.

Where it shows up
  • payment: PaymentMethod
  • parking: PricingPolicy
  • notifications: Notifier
  • vending machine: Dispenser
  • logger: Sink, Formatter
  • mistake: interfaces named
  • after the how, or one
  • interface per class

Interview questions

What is abstraction in object-oriented programming?

Abstraction is exposing only the essential behaviour of something and hiding the implementation details. Callers work with a simplified model, such as an interface with a few methods, and do not need to know how those methods are carried out.

How is abstraction different from encapsulation?

Abstraction is about choosing what to expose: the operations a caller can rely on. Encapsulation is about protecting what is hidden by restricting access, for example with private fields. Abstraction is a design decision; encapsulation is the mechanism that enforces it.

How do you achieve abstraction in Java?

Mainly through interfaces and abstract classes, which declare what operations exist without fixing how they work. Concrete classes provide the implementations, and callers hold references of the abstract type. Even a well-named private method is a small abstraction.

What is a leaky abstraction?

An abstraction that forces callers to know about the details it was meant to hide, for example a repository interface whose callers must handle SQL errors, or code that checks the concrete type behind an interface. The fix is usually to reshape the contract.

What does "one level of abstraction per method" mean?

A method should mix only steps at the same level of detail. A high-level method reads as a sequence of named steps, and lower-level details such as string building or SQL live in the helper methods or classes it calls. This makes code much easier to read.

Why does abstraction make code easier to test?

If a class depends on an interface rather than a concrete class, a test can pass in a simple fake or stub implementation. The test then runs fast, needs no external systems, and can check exactly how the class used its dependency.

Can you have too much abstraction?

Yes. Interfaces with a single implementation that will never vary, deep layers of wrappers and generic frameworks for one use case all add indirection without benefit. Abstract where behaviour really varies, at system boundaries, or where tests need a seam.