Inheritance and interface implementation are subtyping: every SavingsAccount is an Account. Callers who know only the supertype must not be surprised (Liskov Substitution Principle).
Mental model: the subtype may add promises; it must not weaken the ones the supertype already made (preconditions, postconditions, exceptions, thread-safety, equals if documented).
Effective Java: design for inheritance or forbid it (final). The middle ground is how production bugs are born.
extends inherits fields and methods (subject to access). Constructors are not inherited; subclasses chain with super(...).@Override is not optional in professional code — it turns typos into compile errors.super.method() calls the superclass implementation. Use it deliberately; a class that needs super everywhere is poorly factored.abstract methods force subclasses to implement. Abstract classes may have state and constructors.final class or method closes extension.public class Account {
private final String id;
protected Money balance;
public Account(String id, Money balance) {
this.id = Objects.requireNonNull(id);
this.balance = Objects.requireNonNull(balance);
}
public void withdraw(Money amount) { /* invariant: balance >= 0 */ }
}
public final class SavingsAccount extends Account {
public SavingsAccount(String id, Money balance) { super(id, balance); }
}
Fragile base class: the superclass later adds a method your subclass already used for something else, or a superclass method starts calling an overridable method you implemented under old assumptions. Prefer composition or final.
| Rule | Detail |
|---|---|
| Signature | Same name + same erased parameters. Return type may be covariant (subtype). |
| Access | Must be at least as visible (cannot override public with protected). |
| Exceptions | Must not add checked exceptions. May drop them or use subtypes. |
| static / private / final | Cannot override. static hides; private is a new method. |
| Dispatch | Instance methods are virtual: the runtime class wins. |
class Pet { String speak() { return "…"; } }
class Dog extends Pet { @Override String speak() { return "woof"; } }
Pet p = new Dog();
p.speak(); // "woof"
Fields and static methods are not virtual. p.field uses the declared type. Do not hide fields.
An interface is a type that a class can implement in addition to its one superclass. From Java 8 onward interfaces may have:
abstract instance methods (the usual API).default instance methods with a body (evolution without breaking implementors).static methods (factories, helpers).private methods (Java 9) to share code between defaults.Interfaces still cannot hold instance fields (only public static final constants — prefer not to). They cannot be constructed.
public interface Repository<T> {
Optional<T> findById(String id);
void save(T entity);
default boolean exists(String id) { return findById(id).isPresent(); }
}
If two interfaces provide the same default method, the class must override and pick (or combine). A class method always wins over a default. A superclass method wins over an interface default (class wins).
UnsupportedOperationException.A functional interface has exactly one abstract method (SAM). @FunctionalInterface makes the compiler enforce that. Lambdas and method references implement them.
@FunctionalInterface
interface Tax { Money apply(Money net); }
Tax gst = net -> net.plusPercent(18);
Tax gst2 = this::gst18;
JDK examples: Predicate, Function, Consumer, Supplier, Comparator, Runnable. Prefer these over homemade SAMs when they fit. See Streams, Optional, and Lambdas.
Sealed (Java 17): public sealed interface Shape permits Circle, Rect {}. Subtypes are final, sealed, or non-sealed. Exhaustive switch over sealed types is possible (pattern matching for switch is standard in Java 21; on 17 it was preview — use if/instanceof on 17 unless you enable previews).
Enums are classes: they can implement interfaces, have methods and fields, and each constant is a singleton. An enum with abstract methods makes each constant supply an implementation — a clean strategy object.
enum Op {
PLUS { double apply(double a, double b) { return a + b; } },
TIMES { double apply(double a, double b) { return a * b; } };
abstract double apply(double a, double b);
}
Prefer that over switch (op) scattered through the codebase — unless you are on Java 21 and a sealed hierarchy + switch is the clearer model.
// LSP failure — a square is not a mutable rectangle
class Rectangle { void setWidth(int w); void setHeight(int h); }
class Square extends Rectangle {
void setWidth(int w) { super.setWidth(w); super.setHeight(w); }
}
A caller who sets width and height independently has a broken square. Model immutably, or do not inherit.
Stack extends Vector in the JDK is a historical warning: you inherit a huge surface you cannot police. Write a small type that has a list.
Collections.unmodifiableList is this idea.Exception in an override and swallowing — you just violated the contract.final classes and composition.@Override. Know hiding vs overriding (static/fields).~ Good luck with your revision! ~