Abstract class or interface: choosing the abstraction and avoiding half-built objects
Why callers should depend on a contract rather than a concrete implementation; how to choose between an interface, an abstract class, a sealed interface and composition; object initialization order and the overridable-call-in-constructor trap (including Java 25's new fix); how to review a class hierarchy an AI wrote.
On this page
1. The problem
CheckoutService calls StripeClient directly in 14 places. Adding VNPay means editing all 14, and every checkout test hits the Stripe sandbox, adding 6 minutes to CI. The first refactor moves shared code into BasePaymentGateway; on staging, VnpayGateway throws a NullPointerException at startup.
2. Key idea
Callers should only know the contract. Implementations can share in two ways: only the contract (interface), or state plus a processing skeleton (abstract class).
| Interface | Abstract class | |
|---|---|---|
| Instance fields | No (constants only) | Yes |
| Constructor | No | Yes |
| Methods with bodies | default, static, private |
Any |
| Per class | Many | One |
2.1 Which one?
Default to an interface. Move to a parent class only when the implementations really share state and a fixed skeleton.
| Tool | Use when | Don't use when |
|---|---|---|
| Interface | component boundaries, mocking, unrelated classes with one capability (Comparable) |
you just want a place to put shared code |
| Abstract class | one family sharing fields and a skeleton (Template Method) | a subclass has to "switch off" a parent method |
| Sealed interface | a fixed set of variants: payment results, order states | outsiders need to plug in implementations |
| Composition | reusing a few helper functions |
2.2 In what order is an object built?
Static before instance, parent before child. But dynamic dispatch still picks the child's override, so a parent constructor calling an override makes it read child fields that are still null. That's the NPE in section 1.
3. In Java
public interface PaymentGateway { // contract: no state
PaymentResult charge(String orderId, BigDecimal amount);
default boolean supportsRefund() { return false; } // evolve the API without breaking old classes
}
public abstract class HttpGateway implements PaymentGateway {
private final ApiClient api;
protected HttpGateway(ApiClient api) { this.api = api; } // no overridable calls here
public final PaymentResult charge(String orderId, BigDecimal amount) {
return parse(api.post(buildRequest(orderId, amount))); // Template Method
}
protected abstract ApiRequest buildRequest(String orderId, BigDecimal amount);
protected abstract PaymentResult parse(ApiResponse response);
}
public sealed interface PaymentResult permits Success, Failure { }
// switch (result) { case Success s -> ...; case Failure f -> ...; } // compiler checks every caseOther languages: C# has both interface (with default methods) and abstract class; Go has only implicit interfaces and struct embedding.
Clashing defaults, and Java 25's fix for the constructor trap
If two interfaces both have default String hello(), the compiler forces the class to override; call each one with A.super.hello(). Without a clash, a class method always beats a default.
Three fixes for the constructor trap:
- Constructors only call
private,staticorfinalmethods. - Pass a precomputed value through
super(value), or use a factory method that runs the subclass-dependent step after construction. - Java 25 lets you write statements before
super()(flexible constructor bodies):Child(String n) { this.name = n; super(); }. Only fields without an initializer can be assigned there.
javac -Xlint:this-escape warns when a constructor of a public class calls an overridable method.
4. Working with AI
Hand to AI: drawing a class diagram from existing code, generating a FakeGateway for tests, writing one contract test that runs against every implementation.
Check yourself in AI-written code:
- Callers take the interface, not a concrete class or a
Base…class. - No method throws
UnsupportedOperationExceptionor has an empty body just to "satisfy the contract". - Constructors don't call overridable methods;
-Xlint:this-escapeshows no new warnings. - A closed set of variants uses
sealed, and noswitchhas adefaultthat swallows new variants.
5. Exercises
Exercise 1: Review the AI's BaseNotifier
The AI's PR description: "Refactor only, no behavior change." On staging, EmailNotifier throws a NullPointerException at startup. Find the bug, name a test that proves it, fix it.
abstract class BaseNotifier {
private final String template;
protected BaseNotifier() { this.template = loadTemplate(); }
protected abstract String loadTemplate();
}
class EmailNotifier extends BaseNotifier {
private final Path templateDir = Path.of("/etc/notify");
@Override protected String loadTemplate() {
return Files.readString(templateDir.resolve("email.txt"));
}
}Solution 1
The BaseNotifier constructor runs before templateDir is assigned, but dispatch still calls EmailNotifier.loadTemplate(). templateDir is still null, so resolve throws. Test: a unit test that only does new EmailNotifier() fails.
Fixes:
- The subclass reads the file and calls
super(template), or use a factoryEmailNotifier.create(dir). - Better: drop the parent. The template is data; pass a
TemplateLoaderin through composition.
The PR description is wrong too: changing initialization order is a behavior change.
Exercise 2: Choose between two designs
A hotel has receptionists and housekeepers; only housekeepers get rooms assigned. The AI offers two designs: (A) abstract class Employee with assign(Room), and Receptionist overrides it with throw new UnsupportedOperationException(); (B) Employee implements Payable, and only Housekeeper also implements RoomAssignable. Pick one, give the reason and the condition that would flip it.
Solution 2
Pick B. In A, Receptionist takes on a contract it can't keep: a caller holding an Employee can't tell whether assign is safe (breaks Liskov and Interface Segregation). In B, only RoomAssignable implementers get rooms, and payroll() needs no if on employee type.
The choice flips if every employee type handles rooms: then assign belongs to the shared contract. If pay rules depend on the employment contract rather than the type, extract a SalaryPolicy and use composition.
Summary
- Callers depend on an interface by default; an abstract class only when one family shares state and a skeleton.
- Interfaces have no state; clashing defaults force an override that calls
A.super.method(). - Sealed + record +
switch: the compiler checks every case. - Static before instance, parent before child; never call overridable methods from a constructor.
- A method that throws
UnsupportedOperationExceptionsignals a wrong contract.
Further reading: SOLID with Java examples.
Comments
Community rules