Skip to lesson

Adapter: wrapping an incompatible API

ShopLite's checkout must charge cards through a new payment company, but its code has different method names, units and error codes. How do you plug it in without rewriting checkout?

The problem: an SDK that does not fit

An adapter is a small class that makes one interface look like another, so your code can use a class it was never written for.

ShopLite's checkout calls PaymentGateway.pay(orderId, rupees). A new provider, PayNow, ships a library with charge(amountInPaise, merchantRef). Example 1 shows checkout calling it directly.

Example 1 · Without an adapter: SDK details leak into checkout

NoAdapterDemo.javaJava
class PayNowClient {                         // third-party SDK: we cannot edit it    int charge(long amountInPaise, String merchantRef) {        System.out.println("  PayNow: " + amountInPaise + " paise, ref " + merchantRef);        return amountInPaise <= 500000 ? 0 : 51;   // 0 = success, 51 = limit exceeded    }}
class Checkout {    private final PayNowClient payNow = new PayNowClient();
    void placeOrder(String orderId, int rupees) {        long paise = rupees * 100L;                    // SDK unit, inside checkout        int code = payNow.charge(paise, "SHOPLITE-" + orderId);        if (code == 0) {            System.out.println("Order " + orderId + " paid");        } else {            System.out.println("Order " + orderId + " failed, code " + code);        }    }}
public class NoAdapterDemo {    public static void main(String[] args) {        Checkout checkout = new Checkout();        checkout.placeOrder("A101", 1499);        checkout.placeOrder("A102", 7200);    }}
Output
  PayNow: 149900 paise, ref SHOPLITE-A101
Order A101 paid
  PayNow: 720000 paise, ref SHOPLITE-A102
Order A102 failed, code 51

What this code does

  • Checkout knows the SDK's class name, its unit (paise), its reference format and its code numbers. Each of these is a reason to edit checkout when PayNow changes.
  • Rs 7,200 is 7,20,000 paise, above PayNow's limit of 5,00,000 paise, so the SDK returns code 51. Checkout can only print the raw number.

PayNow gives you an SDK (software development kit): a ready library of classes you call but cannot edit. This one wants paise instead of rupees and returns a number code instead of a result object, so every detail leaks into checkout.

Predict the output

What does PayNow charge?

Checkout forgot to convert rupees to paise. Pick the amount the customer pays.

Round 1 of 2

A Rs 1,499 order is passed to the SDK as it is.

int rupees = 1499;
client.charge(rupees, "SHOPLITE-A1");
1 rupee = 100 paise. Mixing the two units is a classic payment bug: the customer pays Rs 14.99 instead of Rs 1499.

Object adapter: implement the target, hold the SDK

An object adapter implements the interface your code expects and keeps the incompatible object in a field. Each method converts the call and forwards it.

PayNowAdapter implements PaymentGateway and holds a PayNowClient in a field. Example 2 also adds a FakeGateway, so the same checkout runs with either one.

Checkout calls the PaymentGateway interface, the target. PayNowAdapter implements PaymentGateway and calls PayNowClient, the third-party SDK, the adaptee. The adapter converts rupees to paise and codes to messages, so checkout never sees the SDK.

Example 2 · Object adapter: PayNowAdapter implements PaymentGateway

ObjectAdapterDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {                       // the target: what checkout expects    PaymentResult pay(String orderId, int rupees);}
class PayNowClient {                              // the adaptee: third-party SDK    int charge(long amountInPaise, String merchantRef) {        System.out.println("  PayNow: " + amountInPaise + " paise, ref " + merchantRef);        return amountInPaise <= 500000 ? 0 : 51;    }}
class PayNowAdapter implements PaymentGateway {    private final PayNowClient client;            // the adaptee is held, not extended
    PayNowAdapter(PayNowClient client) {        this.client = client;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        int code = client.charge(rupees * 100L, "SHOPLITE-" + orderId);        return code == 0                ? new PaymentResult(true, "paid")                : new PaymentResult(false, "declined (PayNow code " + code + ")");    }}
class FakeGateway implements PaymentGateway {    @Override    public PaymentResult pay(String orderId, int rupees) {        return new PaymentResult(true, "paid (fake)");    }}
class Checkout {    private final PaymentGateway gateway;
    Checkout(PaymentGateway gateway) {        this.gateway = gateway;    }
    void placeOrder(String orderId, int rupees) {        PaymentResult result = gateway.pay(orderId, rupees);        System.out.println("Order " + orderId + ": " + result.message());    }}
public class ObjectAdapterDemo {    public static void main(String[] args) {        Checkout real = new Checkout(new PayNowAdapter(new PayNowClient()));        real.placeOrder("A101", 1499);        real.placeOrder("A102", 7200);
        Checkout test = new Checkout(new FakeGateway());        test.placeOrder("T1", 1499);    }}
Output
  PayNow: 149900 paise, ref SHOPLITE-A101
Order A101: paid
  PayNow: 720000 paise, ref SHOPLITE-A102
Order A102: declined (PayNow code 51)
Order T1: paid (fake)

What this code does

  • PayNowAdapter is the only class that knows about paise, the SHOPLITE- reference and code numbers. Checkout sees only PaymentGateway and PaymentResult.
  • The same Checkout class runs with the real adapter and with FakeGateway. Swapping them needs no change inside checkout.

Checkout now depends only on PaymentGateway. It does not know PayNow exists, so a test can pass a fake gateway and a new provider needs only a new adapter. Four roles take part:

  • Target: the interface your code already uses (PaymentGateway).
  • Adaptee: the class with the wrong shape (PayNowClient).
  • Adapter: implements the target and calls the adaptee (PayNowAdapter).
  • Client: the code that uses the target (Checkout).

Order of execution

Build an object adapter

Put the steps in the order you would do them.

Class adapter: adapting through inheritance

A class adapter extends the adaptee and implements the target at the same time, calling the inherited method directly instead of using a field.

PayNowAdapter can also extend PayNowClient and implement PaymentGateway at once. Example 3 shows it working, and the weakness that comes with it.

Example 3 · Class adapter: extends the SDK, and the SDK leaks out

ClassAdapterDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class PayNowClient {    int charge(long amountInPaise, String merchantRef) {        System.out.println("  PayNow: " + amountInPaise + " paise, ref " + merchantRef);        return 0;    }}
class PayNowClassAdapter extends PayNowClient implements PaymentGateway {    @Override    public PaymentResult pay(String orderId, int rupees) {        int code = charge(rupees * 100L, "SHOPLITE-" + orderId);   // inherited method        return new PaymentResult(code == 0, code == 0 ? "paid" : "declined");    }}
public class ClassAdapterDemo {    public static void main(String[] args) {        PayNowClassAdapter adapter = new PayNowClassAdapter();
        PaymentGateway gateway = adapter;        System.out.println("Through the target: " + gateway.pay("A103", 250).message());
        int code = adapter.charge(99, "RAW-CALL");   // the SDK method is public on the adapter        System.out.println("Direct SDK call returned " + code);    }}
Output
  PayNow: 25000 paise, ref SHOPLITE-A103
Through the target: paid
  PayNow: 99 paise, ref RAW-CALL
Direct SDK call returned 0

What this code does

  • The class adapter has no field: it is a PayNowClient and a PaymentGateway at once, so pay calls the inherited charge directly.
  • Because it is also a PayNowClient, any caller holding the adapter can call charge and skip the rupee conversion and the reference format. This is one reason object adapters are preferred.

It works, but it is usually the weaker choice in Java. Java allows only one superclass, so the adapter is tied to that one class. It cannot adapt a final class or an object you receive at runtime, and every public SDK method leaks out through the adapter.

Fix the error

Fix the class adapter

The SDK class is final. Pick the replacement for the highlighted line.

The adapter must compile although the SDK cannot be extended.

final class PayNowClient {
int charge(long amountInPaise, String ref) { return 0; }
}
class PayNowAdapter extends PayNowClient implements PaymentGateway {

Error

error: cannot inherit from final PayNowClient
Prefer the object adapter. It follows composition over inheritance, which the first module of this section explained.

Translating errors at the boundary

The boundary is the edge of your code where it meets an outside system, such as a payment SDK, a database or a web service.

PayNow returns codes like 51 and throws its own checked PayNowException. Example 4 translates both inside the adapter, before checkout sees them.

Example 4 · Translating codes and exceptions in the adapter

ErrorTranslationDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class PaymentFailedException extends RuntimeException {     // ShopLite's own exception    PaymentFailedException(String message, Throwable cause) {        super(message, cause);    }}
class PayNowException extends Exception {                    // the SDK's checked exception    PayNowException(String message) {        super(message);    }}
class PayNowClient {    int charge(long amountInPaise, String merchantRef) throws PayNowException {        if (merchantRef.endsWith("X9")) {            throw new PayNowException("gateway timeout after 30 s");        }        if (amountInPaise <= 0) return 13;                    // invalid amount        if (amountInPaise > 500000) return 51;        return 0;    }}
class PayNowAdapter implements PaymentGateway {    private final PayNowClient client;
    PayNowAdapter(PayNowClient client) {        this.client = client;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        try {            int code = client.charge(rupees * 100L, "SHOPLITE-" + orderId);            return switch (code) {                case 0 -> new PaymentResult(true, "paid");                case 13 -> new PaymentResult(false, "invalid amount");                case 51 -> new PaymentResult(false, "card limit exceeded");                default -> new PaymentResult(false, "declined (code " + code + ")");            };        } catch (PayNowException e) {            throw new PaymentFailedException("payment provider not reachable, please retry", e);        }    }}
public class ErrorTranslationDemo {    public static void main(String[] args) {        PaymentGateway gateway = new PayNowAdapter(new PayNowClient());        String[] ids = {"A201", "A202", "A203", "X9"};        int[] amounts = {1499, 7200, 0, 650};
        for (int i = 0; i < ids.length; i++) {            try {                PaymentResult r = gateway.pay(ids[i], amounts[i]);                System.out.println(ids[i] + ": " + r.message());            } catch (PaymentFailedException e) {                System.out.println(ids[i] + ": " + e.getMessage());                System.out.println("    cause: " + e.getCause().getMessage());            }        }    }}
Output
A201: paid
A202: card limit exceeded
A203: invalid amount
X9: payment provider not reachable, please retry
    cause: gateway timeout after 30 s

What this code does

  • The switch turns PayNow's numbers into messages ShopLite understands. A new code from PayNow changes one line in one class.
  • The checked PayNowException never leaves the adapter. It is wrapped in the unchecked PaymentFailedException, and e.getCause() still holds the original for the logs.

The adapter sits exactly at the boundary, so it turns codes into readable PaymentResult messages and wraps the exception in ShopLite's own PaymentFailedException, keeping the original as the cause. Checkout never imports an SDK type.

Three rules keep the boundary clean:

  • Keep one adapter per outside system, in its own package (for example payment.paynow).
  • Convert units (paise, dates, currencies) in the adapter, nowhere else.
  • Never turn a failure into a success, and never swallow the original exception: pass it as the cause.

Find the bug

Find the leaking line

Each adapter method has one bug. Click the wrong line.

The SDK declined the payment but the order shows paid.

Round 1 of 2

Adapters in the JDK: Arrays.asList and InputStreamReader

Example 5 uses two adapters that ship with the JDK: Arrays.asList and InputStreamReader.

Example 5 · Two JDK adapters: Arrays.asList and InputStreamReader

JdkAdaptersDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.nio.charset.StandardCharsets;import java.util.Arrays;import java.util.List;
public class JdkAdaptersDemo {    public static void main(String[] args) throws IOException {        String[] seats = {"S1-12", "S1-13", "S1-14"};        List<String> view = Arrays.asList(seats);          // array seen as a List        view.set(0, "B2-40");        System.out.println("Array after list.set: " + seats[0]);        try {            view.add("S1-15");        } catch (UnsupportedOperationException e) {            System.out.println("list.add: UnsupportedOperationException");        }
        byte[] bytes = "Order A101 placed".getBytes(StandardCharsets.UTF_8);        InputStream in = new ByteArrayInputStream(bytes);                 // gives bytes        Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8); // gives chars        StringBuilder text = new StringBuilder();        int ch;        while ((ch = reader.read()) != -1) {            text.append((char) ch);        }        reader.close();        System.out.println("Read " + bytes.length + " bytes as text: " + text);    }}
Output
Array after list.set: B2-40
list.add: UnsupportedOperationException
Read 17 bytes as text: Order A101 placed

What this code does

  • Arrays.asList does not copy the array. The list forwards set to the array underneath, so seats[0] changes too, and add fails because an array has a fixed size.
  • InputStreamReader is the adapter, the byte stream is the adaptee and Reader is the target. The loop only knows Reader, so it would work the same over a file or network stream.

Arrays.asList(array) adapts an array to the List interface. The list is a view over the same array: set writes into the array, and add or remove throw UnsupportedOperationException because an array cannot grow.

InputStreamReader adapts an InputStream, which gives raw bytes, to a Reader, which gives characters. It uses a charset (a table such as UTF-8 that maps bytes to characters), so code written for Reader can read from any byte source.

Next step

Check your understanding

12 quick questions