- Prerequisites
- 5.1 Encapsulation
- Covers
- Abstract classes · Abstract methods · Interfaces · Contract-based design
- Related
- 7.1 Interfaces · 7.4 Interface-Based Design · 6.3 Polymorphism · Book 5 Vol IV (Template Method, Strategy)
On this page
1Concept / Definition
Abstraction means representing something by its essential behaviour while leaving out details that do not matter to the user of it. In code, an abstraction is a type — an interface or abstract class — that defines what can be done without committing to how. Code that depends on the abstraction works with any implementation that honours it.
Every program is a stack of abstractions. A controller calls a service without knowing how orders are stored; the service calls a repository without knowing SQL; the repository uses JDBC without knowing the database's page format. Each layer is simpler to use than what it hides.

2Why It Exists
Human working memory is small. Abstraction lets a developer think about paymentGateway.charge(amount, card) without holding the details of HTTP, TLS, retries and a provider's API in mind. It also lets implementations vary — a different payment provider, a test fake, a new storage engine — without changing the code that uses them. Abstraction is therefore the enabler of polymorphism (6.3), dependency inversion (7.4) and testability.
3Core Concepts
Abstract classes
An abstract class is declared with abstract and cannot be instantiated. It can have fields, constructors, concrete methods and abstract methods. It is used when several related classes share state and implementation, and differ only in some steps. Because Java allows only single inheritance of classes, choosing an abstract base class uses up a subclass's one inheritance slot.

The typical pattern is the Template Method (Book 5): a final public method defines the algorithm, calling protected abstract methods for the steps that vary.
Abstract methods
An abstract method has a signature but no body: protected abstract List<Row> fetchData();. A class with at least one abstract method must itself be abstract, and every concrete subclass must implement all inherited abstract methods. Interface methods without a body are implicitly abstract.
Interfaces
An interface declares a contract — method signatures, and since Java 8 optionally default and static methods, and since Java 9 private methods. It has no instance state and no constructors. A class can implement any number of interfaces, which makes interfaces the primary tool for abstraction in modern Java: define the capability as an interface, and let independent classes implement it.


| Choose an interface when… | Choose an abstract class when… |
|---|---|
| You define a capability or role (Payable, Repository) | Subclasses share significant state and code |
| Unrelated classes may implement it | Classes are a family of closely related types |
| Implementations may need to extend other classes | You need constructors or protected state |
| You want easy test doubles and multiple implementations | You want to fix an algorithm and vary steps (Template Method) |
Contract-based design
An abstraction is only useful if its behaviour is specified. Design by contract, from Bertrand Meyer, describes a method's contract in three parts:

Java has no built-in contract language, so contracts are expressed through: precise types (Money rather than double); Javadoc stating preconditions, postconditions and thrown exceptions; runtime checks with Objects.requireNonNull and argument validation; and tests that any implementation must pass. The Liskov Substitution Principle (6.4, Book 5) requires every implementation to honour the contract of its abstraction: no stronger preconditions, no weaker postconditions.
4How It Works Internally
An abstract class compiles to an ordinary class file with the ACC_ABSTRACT flag; the JVM refuses to instantiate it. Abstract methods have no Code attribute. Calls through an abstraction use invokevirtual (abstract class) or invokeinterface (interface), dispatched at run time to the object's actual class. When only one implementation has been loaded, the JIT can inline through the abstraction as if it were a direct call, deoptimising if another implementation appears later (1.2). In practice, abstraction usually costs nothing at run time.
Default methods are ordinary methods stored in the interface's class file. When a class inherits more than one implementation of the same method, three rules decide which one runs, and javac applies them at compile time as well: a method declared in the class or any superclass wins over every default; among interfaces, the most specific one wins, so a sub-interface beats the interface it extends; and if two unrelated interfaces still both supply a default, the class must override the method, and may pick one explicitly with Greeter.super.greet(). Q12 shows the first two rules.
5APIs / Features / Syntax
public interface PaymentGateway {
/**
* Charges the card.
* @param amount must be positive
* @return a receipt; never null
* @throws PaymentDeclinedException if the provider declines the charge
*/
Receipt charge(Money amount, Card card);
void refund(Receipt receipt);
// optional behaviour
default boolean supports(Currency currency) { return true; }
}
public abstract class ReportGenerator {
public final Path generate() { // template method: fixed algorithm
List<Row> rows = fetchData();
byte[] content = format(rows);
return write(content);
}
protected abstract List<Row> fetchData(); // steps that vary
protected abstract byte[] format(List<Row> rows);
private Path write(byte[] content) { … } // shared step
}6Practical Examples
Example 1 — Client code depends on the abstraction
public class CheckoutService {
private final PaymentGateway gateway; // abstraction, not CardGateway
public CheckoutService(PaymentGateway gateway) {
this.gateway = gateway;
}
public Receipt checkout(Order order, Card card) {
return gateway.charge(order.total(), card);
}
}
// Production wiring
new CheckoutService(new CardGateway(apiKey));
// Test wiring
new CheckoutService(new FakeGateway());Example 2 — Mini program: one contract, two implementations, the same checks
Problem. Example 3 expresses the contract as an abstract JUnit test. This mini program does the same without a test framework, so it runs on its own: an interface whose Javadoc states the contract, two implementations that both compile, and one verify method that every implementation must pass.
public class ContractCheck {
record Receipt(String id, BigDecimal amount) {}
/** Contract: charge rejects amount <= 0 with IllegalArgumentException and
* never returns null; a receipt can be refunded once, a second refund
* throws IllegalStateException. */
interface PaymentGateway {
Receipt charge(BigDecimal amount);
void refund(Receipt receipt);
}
static final class FakeGateway implements PaymentGateway {
private final Set<String> refunded = new HashSet<>();
private int next = 1;
public Receipt charge(BigDecimal amount) {
if (amount.signum() <= 0)
throw new IllegalArgumentException("amount must be > 0");
return new Receipt("R" + next++, amount);
}
public void refund(Receipt receipt) {
if (!refunded.add(receipt.id()))
throw new IllegalStateException("already refunded");
}
}
static final class SloppyGateway implements PaymentGateway { // compiles fine
public Receipt charge(BigDecimal amount) {
return amount.signum() > 0 ? new Receipt("S1", amount) : null;
}
public void refund(Receipt receipt) { } // no check
}
static void verify(String name, Supplier<PaymentGateway> factory) {
List<String> failures = new ArrayList<>();
PaymentGateway g = factory.get();
Receipt r = g.charge(new BigDecimal("100.00"));
if (r == null) failures.add("null receipt");
try {
if (g.charge(BigDecimal.ZERO) == null)
failures.add("null for amount 0");
else failures.add("accepted amount 0");
} catch (IllegalArgumentException expected) { }
if (r != null) {
g.refund(r);
try { g.refund(r); failures.add("refunded twice"); }
catch (IllegalStateException expected) { }
}
System.out.println(name
+ (failures.isEmpty() ? "PASS" : "FAIL " + failures));
}
public static void main(String[] args) {
verify("FakeGateway ", FakeGateway::new);
verify("SloppyGateway ", SloppyGateway::new);
}
}FakeGateway PASS
SloppyGateway FAIL [null for amount 0, refunded twice]
Why it behaves this way. Both classes implement PaymentGateway, so the compiler accepts both: it checks signatures, not behaviour. SloppyGateway returns null for a zero amount instead of throwing, and accepts a second refund. Code written against the contract never checks for null and relies on a repeated refund being rejected, so it would fail only after this implementation is plugged in, a violation of the Liskov Substitution Principle in two lines. Running the same checks against every implementation, as verify does here and the abstract test class does in Example 3, turns the Javadoc into something that can fail a build (Figure 6).
Example 3 — A contract test every implementation must pass
abstract class PaymentGatewayContractTest {
protected abstract PaymentGateway gateway();
@Test void chargeReturnsReceiptForValidCard() {
assertNotNull(gateway().charge(Money.inr("100.00"), TestCards.VALID));
}
@Test void chargeRejectsNonPositiveAmount() {
assertThrows(IllegalArgumentException.class,
() -> gateway().charge(Money.inr("0.00"), TestCards.VALID));
}
}
class FakeGatewayTest extends PaymentGatewayContractTest {
protected PaymentGateway gateway() { return new FakeGateway(); }
}Example 4 — A Template Method you can run
Problem. Section 5's ReportGenerator shows the shape of a Template Method, but its shared step is elided. This version runs: an abstract class with a constructor, a final algorithm, two abstract steps and a hook with a default.
public class TemplateReport {
record Row(String sku, int qty) {}
abstract static class ReportGenerator {
private final String title;
protected ReportGenerator(String title) { // runs for each subclass
this.title = title;
}
public final String generate(List<Row> rows) { // the fixed algorithm
StringBuilder out = new StringBuilder(header(title));
for (Row row : rows) out.append(line(row));
return out.append(footer(rows.size())).toString();
}
protected abstract String header(String title); // steps that vary
protected abstract String line(Row row);
protected String footer(int count) { // hook with a default
return count + " rows\n";
}
}
static final class CsvReport extends ReportGenerator {
CsvReport() { super("stock"); }
protected String header(String t) { return "# " + t + "\nsku,qty\n"; }
protected String line(Row r) { return r.sku() + "," + r.qty() + "\n"; }
}
static final class TextReport extends ReportGenerator {
TextReport() { super("STOCK"); }
protected String header(String t) { return t + "\n"; }
protected String line(Row r) {
return String.format("%-6s%4d", r.sku(), r.qty()) + "\n";
}
@Override protected String footer(int count) {
return "-- " + count + " items --\n";
}
}
public static void main(String[] args) {
List<Row> rows = List.of(new Row("PEN", 40), new Row("BOOK", 7));
System.out.print(new CsvReport().generate(rows));
System.out.print(new TextReport().generate(rows));
}
}# stock
sku,qty
PEN,40
BOOK,7
2 rows
STOCK
PEN 40
BOOK 7
-- 2 items --Why it behaves this way. generate is final, so no subclass can change the order of the steps; subclasses supply only header and line, and may override the footer hook. Each subclass constructor calls the abstract class's constructor with super(title), which is the answer to Q2: an abstract class cannot be instantiated, but its constructor runs as part of creating every subclass object and initialises the state they share. TextReport appends "\n" itself instead of using the %n format, which writes the platform's line separator, \r\n on Windows, and would make the output differ between machines.
Example 5 — Leaky abstraction
// Looks like a simple in-memory loop over customers...
for (Customer c : customerRepository.findAll()) {
// ...but each call may run a SQL query (N+1)
total += c.getOrders().size();
}
Example 6 — The leak measured: lazy loading versus one batch query
Problem. Example 5 says that a loop over findAll() may run one query per customer. This program simulates a repository with lazy loading and counts the queries, then fetches the same data the way an explicit batch query would.
public class NPlusOne {
static int queries; // what the abstraction hides
record Order(long customerId, int amount) {}
static final class Customer {
final long id;
private List<Order> orders; // loaded on first use
Customer(long id) { this.id = id; }
List<Order> orders() {
if (orders == null) orders = Db.ordersOf(id); // one query each
return orders;
}
}
static final class Db { // stands in for SQL
static List<Customer> customers() {
queries++;
List<Customer> all = new ArrayList<>();
for (long id = 1; id <= 100; id++) all.add(new Customer(id));
return all;
}
static List<Order> ordersOf(long id) {
queries++;
return List.of(new Order(id, 10), new Order(id, 20));
}
static Map<Long, List<Order>> ordersOf(Collection<Long> ids) {
queries++; // one IN (...) query
Map<Long, List<Order>> byId = new HashMap<>();
for (long id : ids)
byId.put(id, List.of(new Order(id, 10), new Order(id, 20)));
return byId;
}
}
public static void main(String[] args) {
int total = 0;
for (Customer c : Db.customers()) total += c.orders().size();
System.out.println("lazy loop: " + total + " orders, "
+ queries + " queries");
queries = 0;
List<Customer> customers = Db.customers();
Map<Long, List<Order>> orders =
Db.ordersOf(customers.stream().map(c -> c.id).toList());
total = orders.values().stream().mapToInt(List::size).sum();
System.out.println("batch: " + total + " orders, "
+ queries + " queries");
}
}lazy loop: 200 orders, 101 queries
batch: 200 orders, 2 queries
Why it behaves this way. The loop looks like work in memory, but each first call to c.orders() goes back to the database, so 100 customers cost 101 queries. At 1 ms per round trip that is a tenth of a second for one page, and it grows with the data: the abstraction hid the access pattern but not its cost. The batch version asks for the orders of all customers in one query, so the count stays at 2 whatever the number of customers. JPA offers the same fix through JOIN FETCH, entity graphs or batch fetching, but someone has to know what the abstraction hides to choose it (Figure 8).
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Interface for every class, with exactly one implementation forever | Indirection without benefit | Introduce an interface when there is a real reason: variation, testing boundary, module boundary |
| Abstraction modelled on one implementation (leaking provider-specific types) | Cannot swap implementation | Design the contract from the client's needs |
| Undocumented contracts | Implementations behave differently; bugs on substitution | Document pre/postconditions and exceptions; contract tests |
| Deep abstract class hierarchies | Hard to understand, fragile | Interfaces plus composition (Chapter 7) |
| Ignoring leaks (latency, N+1, failure) | Performance and reliability incidents | Know what the abstraction hides; measure |
| Adding an abstract method to a published interface | Every implementation outside your code stops compiling, and old binaries fail with AbstractMethodError | Add a default method, or a new interface that extends the old one |
| A Template Method whose template is not final | A subclass overrides the algorithm itself and skips steps such as validation or auditing | Make the template final and the steps protected (Example 4) |
| A provider's exception types leaking through the abstraction | Callers catch the provider's exceptions, so they depend on that provider after all | Translate them into exceptions the abstraction declares |
8Performance & Production Considerations
- Interface and virtual calls are usually inlined by the JIT when only one or two implementations are in use; the cost of abstraction is typically zero.
- The expensive leaks are semantic: a repository call that is a network round trip, a remote client that looks local, a collection whose
getis O(n). Production issues often start where a developer trusted an abstraction's simplicity too far. - An abstraction over a remote call must state its failure modes. A
PaymentGatewaythat calls a provider can be slow, time out or fail half-way. Its contract should say which exceptions mean "not charged" and which mean "outcome unknown", because callers decide from that whether a retry is safe.
9Architecture & Design Considerations
Abstraction is the basic tool for managing change across a system. Well-placed abstractions sit at the points where change is expected: external providers (payment, messaging), infrastructure (storage, caches), and policies that vary (pricing rules). Hexagonal and clean architectures formalise this: the domain defines ports (interfaces), and infrastructure provides adapters (implementations).
10Interview Questions & Answers
What is abstraction in object-oriented programming?
Modelling something by its essential behaviour and hiding irrelevant details, usually through interfaces or abstract classes that define what can be done without specifying how.
Can an abstract class have a constructor? Can it be instantiated?
It can have constructors, which run when a concrete subclass is instantiated, to initialise the inherited state. It cannot be instantiated directly. Example 4 shows the constructor at work.
What is the difference between an abstract class and an interface in modern Java?
An abstract class can have instance fields, constructors and any kind of method, and a class can extend only one. An interface has no instance state or constructors but can have abstract, default, static and private methods, and a class can implement many. Interfaces model capabilities; abstract classes share implementation among closely related classes.
Why do interfaces have default methods, and what are their risks?
They were added in Java 8 so interfaces such as Collection could gain new methods (stream, forEach) without breaking existing implementations. Risks: conflicts when a class implements two interfaces with the same default (the class must resolve it), and interfaces accumulating implementation logic they should not own.
What is contract-based design?
Specifying each method by preconditions (what the caller must ensure), postconditions (what the method guarantees) and invariants (what always holds). In Java this is expressed with precise types, Javadoc, validation checks and contract tests, and it is what makes implementations safely substitutable.
When would you choose an abstract class over an interface?
When closely related implementations share significant state and code, need constructors, or follow a fixed algorithm with varying steps (Template Method). Often the best design is both: an interface for the contract, and an optional abstract base class implementing it.
What is a leaky abstraction? Give an example from enterprise Java.
An abstraction whose hidden details affect its users anyway. JPA hides SQL, but lazy loading leaks as N+1 queries and LazyInitializationException; a REST client hides HTTP, but latency, timeouts and partial failures leak. Users must understand what is hidden in order to use it well. Example 6 measures the N+1 case.
Should every service class have an interface?
No. Interfaces are worthwhile at real variation points, module boundaries and external dependencies. A one-to-one interface for every class adds indirection without benefit; modern mocking tools can mock classes directly. Introduce an interface when there is a concrete reason.
How do abstraction and hexagonal architecture relate?
Hexagonal architecture places abstractions — ports — at the boundary of the domain: the domain defines interfaces for what it needs (repositories, payment, notifications), and infrastructure adapters implement them. The domain depends only on its own abstractions, so infrastructure can change without touching business logic.
How do you decide where abstractions belong in a system?
Put them where change or variation is expected and where you need isolation: external providers, infrastructure, policies that vary, module and service boundaries. Avoid speculative abstractions; wait for two or three real cases, and design each abstraction from the consumer's needs.
A platform team proposes a generic "DataAccess" abstraction to hide all databases across 40 services. What do you think?
Be sceptical. A lowest-common-denominator abstraction over very different stores hides exactly the capabilities each service needs (transactions, query models, consistency), leaks anyway, and couples all services to one library's release cycle. Better: shared conventions, templates and observability, with each service choosing a store-appropriate abstraction — a repository per aggregate — at its own boundary.
What does this program print?
public class DefaultQuiz {
interface Greeter { default String greet() { return "interface"; } }
static class Base { public String greet() { return "class"; } }
static class Impl extends Base implements Greeter {}
interface A { default String who() { return "A"; } }
interface B extends A { @Override default String who() { return "B"; } }
static class C implements A, B {}
public static void main(String[] args) {
System.out.println(new Impl().greet() + " " + new C().who());
}
}It prints class B. Impl inherits greet() both from its superclass Base and as a default from Greeter; a method from the class hierarchy always wins over a default, so "class" is printed. C inherits who() from A and from B, and B extends A and overrides it, so B is the more specific interface and its default wins. Had A and B been unrelated, C would not compile until it overrode who() itself (section 4).
Does calling a method through an interface cost more than calling it on the class directly?
In interpreted code slightly, because invokeinterface has to find the method in the receiver's class, but hot code is compiled by the JIT, which profiles each call site. If a site has seen only one or two implementing classes, the JIT inlines them behind a cheap type check, so the call costs the same as a direct one; only sites that see many classes keep a real dispatch. Class hierarchy analysis lets it go further when only one implementation is loaded, with deoptimisation as the safety net if another appears. Interfaces at real boundaries are therefore free in practice; the reasons against needless ones are about design, not speed (Q8).
After a switch to a new payment provider, checkout starts failing in ways no test showed. The new adapter implements PaymentGateway and compiles. What do you look for?
Behaviour the interface does not enforce: does the adapter return null where the old one threw, throw different exception types, treat a repeated refund differently, support the same currencies, or block for longer than callers expect? Run the contract tests of Example 2 against the new adapter first; any failure is the bug. Then check how it maps the provider's errors and timeouts onto the exceptions the abstraction declares, because callers decide on retries from them. Finally, add every difference you found as a new contract test so that the next provider is checked automatically.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Abstraction exposes essential behaviour and hides irrelevant detail.
- Interfaces are the default abstraction tool; abstract classes share implementation among related types.
- A contract — preconditions, postconditions, invariants — makes abstractions substitutable.
- Every non-trivial abstraction leaks; know what it hides.
- Place abstractions where change is expected, designed from the consumer's view.