Object-Oriented Programming in Java
Java was designed around objects, and unlike some languages that added them later, it never had a version without them. A class is not a convenience wrapper around a record of data; it is the unit that owns behaviour, invariants and identity, and the language gives you several ways to define one: a plain class, an interface, an abstract class, a record, an enum, and a sealed type. Choosing between them is the real skill. By the end of this chapter you will be able to read a Java class and say what each modifier is doing, predict which implementation runs when a call appears to be virtual, and know when a record or an enum is a better fit than a hand-written class with getters.
A class is a description; an object is an instance of it. The description holds the state in fields and the behaviour in methods.
public abstract class MediaItem {
private final String sku;
private String title;
private int copiesInStock;
public MediaItem(String sku, String title, int copiesInStock) {
this.sku = sku;
this.title = title;
this.copiesInStock = copiesInStock;
}
public String sku() {
return sku;
}
public String title() {
return title;
}
public void setTitle(String title) {
if (title == null || title.isBlank()) {
throw new IllegalArgumentException("title must not be blank");
}
this.title = title;
}
public int copiesInStock() {
return copiesInStock;
}
public void reduceStock(int copies) {
this.copiesInStock -= copies;
}
public abstract double price();
public String describe() {
return "%s (%s) costs %.2f".formatted(title, sku, price());
}
}
Creating an object is done with the new keyword, which allocates the object, runs the constructor, and returns a reference to it.
Book item = new Book("SKU-1001", "The Pragmatic Programmer", 352);
System.out.println(item.title());
System.out.println(item.describe());
Two details of the design are worth noticing already. sku is final, so it can be assigned only in the constructor and the identity of the item can never change. setTitle rejects blank values, so the class enforces its own invariant rather than trusting every caller to behave.
A class that holds state has identity: two items with the same title are still two different objects. This matters later, when equality is discussed.
A constructor has the same name as the class and no return type.
public MediaItem(String sku) {
this(sku, "Untitled", 0);
}
public MediaItem(String sku, String title) {
this(sku, title, 0);
}
this(...) calls another constructor in the same class, and it has to be the first statement. Chaining constructors in this way means there is exactly one place where the full object is assembled, and the shorter constructors cannot drift out of sync with it.
If a class declares no constructor at all, the compiler supplies a default one that takes no arguments and leaves every field at its default value: zero for numbers, null for references, false for booleans. Once you declare any constructor, the default one disappears, which is a frequent surprise when a class suddenly cannot be instantiated with new.
A field declared final without an initialiser is a blank final, and it must be assigned exactly once, either in the constructor or in an initialiser block. The compiler enforces this, which is how a final field can be trusted afterwards.
this refers to the current object. It is required when a field and a parameter share a name, as in this.title = title, and it is also used to call another method of the same object.
super refers to the direct parent. It appears in two places: super(...) calls the parent constructor, and super.method() calls the parent implementation of an overridden method.
public class Book extends MediaItem {
private final int pages;
public Book(String sku, String title, int pages) {
super(sku, title, 0);
this.pages = pages;
}
public int pages() {
return pages;
}
@Override
public double price() {
return 19.99;
}
@Override
public String describe() {
return super.describe() + " (" + pages + " pages)";
}
}
super(...) must be the first statement of the constructor. If you omit it, the compiler inserts a call to the parent’s no-argument constructor, which is why a parent class without a no-argument constructor produces the error constructor X in class Y cannot be applied to given types.
Encapsulation is the practice of keeping a field private and exposing it only through methods that keep the object’s rules intact. Java offers four levels of access, and the default one is the level people forget.
| Modifier | Visible in | Typical use |
|---|---|---|
private | The declaring class only | Fields and helper methods that must not be touched from outside |
| No modifier, also called package-private | The declaring package | Types meant to be used by collaborators in the same package |
protected | The declaring package and subclasses in other packages | Members that subclasses legitimately need |
public | Everywhere | The public surface of an API |
Two details catch people out. First, the default is package-private, not public, so a class with no modifier is invisible to code in another package even when the package name looks related. Second, protected in Java is wider than “subclasses”: it also grants access to everything in the same package. This differs from C++ and from the common mental model of the keyword.
A nested class can reach the private members of its enclosing class, and the enclosing class can reach the private members of its nested classes. That is why a private constructor does not actually prevent instantiation from inside the class itself.
Java supports single inheritance: a class has at most one direct superclass, but it may implement any number of interfaces. Object is the implicit parent of every class, and it provides toString, equals and hashCode.
public class Book extends MediaItem {
// ...
}
An overriding method must have the same name and parameter types, and its return type must be the same or a subtype of the parent return type, which is called covariant return. Access may be widened but not narrowed, so an overriding method may be public when the parent method is protected, but not the other way round.
@Override
public String describe() {
return super.describe() + " (" + pages + " pages)";
}
The @Override annotation is not required, but it is worth always writing. It makes the compiler check that the method really overrides something, so a typo in the signature becomes a compile error instead of an accidental new method.
Polymorphism means that a reference can point at objects of different types, and that the code operating on the reference calls the right implementation.
MediaItem[] shelf = {
new Book("SKU-1001", "The Pragmatic Programmer", 352),
new Dvd("SKU-1002", "A Wonderful Life", 94),
new Book("SKU-1003", "Clean Code", 464)
};
for (MediaItem item : shelf) {
System.out.println(item.describe());
}
A sibling type is all that Dvd needs to be for this to work.
public class Dvd extends MediaItem {
public Dvd(String sku, String title, int minutes) {
super(sku, title, 0);
}
@Override
public double price() {
return 12.50;
}
}
Each call to item.describe() runs the base implementation, but the price() call inside it is dispatched at runtime to the implementation of the actual object, Book or Dvd. That is dynamic dispatch, and it is what makes a collection of different types usable through one reference.
Three rules decide whether a call is dispatched dynamically.
- An overridden instance method is dispatched dynamically.
- A
staticmethod is not overridden; it is hidden. The version that runs is chosen by the reference type at compile time, not by the object at runtime. - A
privatemethod cannot be overridden at all, and afinalmethod may not be overridden.
An interface describes what an object can do without saying how. Members are public and abstract by default, so an implementing class must supply the bodies.
public interface Discountable {
double discountRate();
default double discounted(double amount) {
return amount * (1 - discountRate());
}
}
The default method has a body, which means an implementing class may simply inherit it. If two interfaces both supply a default method with the same signature, the implementing class has to resolve the conflict by overriding the method and calling Discountable.super.discounted(...) explicitly.
A functional interface has exactly one abstract method, so it can be implemented with a lambda expression.
Discountable memberDiscount = () -> 0.10;
Discountable staffDiscount = () -> 0.25;
System.out.println(memberDiscount.discounted(50.0));
Interfaces may also declare static methods, which are not inherited, and private methods, which exist to share implementation between the default methods of the same interface.
An abstract class is a class that cannot be instantiated and may contain abstract methods. It sits between a concrete class and an interface: it can hold state and constructors, but it still demands that subclasses fill in the missing pieces.
public abstract class PhysicalItem extends MediaItem {
protected final double weightKg;
protected PhysicalItem(String sku, String title, double weightKg) {
super(sku, title, 0);
this.weightKg = weightKg;
}
public abstract double shippingCost();
}
The choice between an abstract class and an interface is usually about state and reuse. Use an interface when the types share no code and no state but must be interchangeable, and use an abstract class when the subtypes genuinely share an implementation and a common base state.
A record (final in Java 16) is a class whose whole purpose is to hold data. The compiler generates the fields, the accessors, equals, hashCode and toString for you.
public record CartLine(String sku, int quantity, BigDecimal unitPrice) {
public CartLine {
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
}
public BigDecimal total() {
return unitPrice.multiply(BigDecimal.valueOf(quantity));
}
}
CartLine line = new CartLine("SKU-1001", 2, new BigDecimal("19.99"));
System.out.println(line.sku()); // accessors are named after the component
System.out.println(line.total());
The compact constructor, written with no parameter list, is where validation belongs: it runs before the field assignment, so a rejected value never reaches the object. Records are implicitly final and extend java.lang.Record, so they cannot extend another class, but they can implement interfaces.
A record is the right choice for a value that is transparent data, such as a tuple, a coordinate, or a line item. It is the wrong choice for a mutable domain object with behaviour and identity.
An enum defines a fixed set of constants. Each constant is a single instance of the enum type, created once when the class is initialised.
public enum MediaType {
BOOK("book", 10.00),
AUDIOBOOK("audiobook", 15.00),
DVD("dvd", 12.00);
private final String code;
private final double basePrice;
MediaType(String code, double basePrice) {
this.code = code;
this.basePrice = basePrice;
}
public String code() {
return code;
}
public double basePrice() {
return basePrice;
}
public static MediaType fromCode(String code) {
for (MediaType type : values()) {
if (type.code.equalsIgnoreCase(code)) {
return type;
}
}
throw new IllegalArgumentException("unknown media type: " + code);
}
}
The semicolon after the last constant separates the constants from the members. values() returns an array of the constants and valueOf(String) looks one up by name, throwing IllegalArgumentException when the name is unknown. Because the constants are singletons, they can be compared with == safely.
A switch expression over an enum must be exhaustive, and the compiler checks that for you, so adding a new constant later produces a compile error rather than a silent fall-through.
String label = switch (type) {
case BOOK -> "Printed book";
case AUDIOBOOK -> "Audio book";
case DVD -> "Disc";
};
A sealed type (final in Java 17) restricts who may extend or implement it. That restriction turns an open hierarchy into one the compiler can reason about, which is exactly what a switch over an interface needs.
public sealed interface Notification permits EmailNotification, SmsNotification {
String recipient();
default String body() {
return "Hello";
}
}
public record EmailNotification(String recipient, String subject) implements Notification {
@Override
public String body() {
return "Subject: " + subject;
}
}
public record SmsNotification(String recipient, String message) implements Notification {
@Override
public String body() {
return message;
}
}
A permitted subclass is either final, sealed again, or non-sealed, which reopens the hierarchy. Without a permits clause the permitted types are taken from the same package or module.
A generic type is a class or method that works with a type parameter rather than a concrete type.
import java.util.function.Function;
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T value() {
return value;
}
public <R> Box<R> map(Function<T, R> mapper) {
return new Box<>(mapper.apply(value));
}
}
Box<String> label = new Box<>("hello");
Box<Integer> length = label.map(String::length);
Type parameters can be bounded from above with an extends clause, and the use of a type can be bounded from below with a super wildcard.
public class NumberBox<T extends Number> { }
List<? extends Number> anyNumbers = new ArrayList<Integer>();
List<? super Integer> numbersThatAcceptIntegers = new ArrayList<Number>();
The wildcard that reads is ? extends, because the compiler can guarantee that the elements are of the declared type. The wildcard that writes is ? super, because the compiler can guarantee that the declared type is acceptable to whatever consumes the list. The rule of thumb is: use ? extends when you read, use ? super when you write.
Generics are implemented with type erasure: at runtime the type information is removed, so List<String> and List<Integer> are the same class. Two consequences follow. A cast to a specific parameterised type is unchecked and only a warning, and instanceof cannot test for a parameterised type at all, though instanceof List<?> is allowed because the wildcard erases to List. Erasure also exists so that a generic class can be used with code written before generics were added to the language.
Every class inherits equals and hashCode from Object, and the default implementations compare identity. A value-like class needs value equality instead.
The contract has four rules:
equalsis reflexive: an object equals itself.equalsis symmetric: ifaequalsb, thenbequalsa.equalsis transitive: ifaequalsbandbequalsc, thenaequalsc.equalsis consistent: the result does not change while the object is unchanged.
And one rule that binds the pair together: objects that are equal must have the same hash code. Hash-based collections such as HashMap and HashSet use the hash code to decide where to look, and then use equals to confirm the match. If two equal objects hash differently, the collection can hold duplicates of the same value, which is a bug that is very hard to find later.
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MediaItem that)) {
return false;
}
return sku.equals(that.sku);
}
@Override
public int hashCode() {
return Objects.hash(sku);
}
Objects.equals(a, b) and Objects.hash(a, b) are null-safe helpers, and overriding one method without the other is the most common way to break the contract. A mutable field must never take part in either method, because changing it changes where the object hashes to.
final means “cannot change after initialisation”, and it means something slightly different in each position.
| Position | Meaning |
|---|---|
| Local variable | Assigned exactly once; the compiler rejects a second assignment |
| Field | Assigned in the declaration, an initialiser block, or the constructor, and never again |
| Method | Cannot be overridden by a subclass |
| Class | Cannot be extended; String is final for exactly this reason |
static means “belongs to the class rather than to an instance”.
- A static field is shared by every instance, which makes it the natural place for a constant:
public static final int MAX_ITEMS = 500; - A static method is called on the class, not on an object, and cannot use instance state.
Math.maxandObjects.hashare examples. - A static nested class does not need an instance of its outer class, and it is the usual way to group a helper type that belongs to a class without being part of its public surface.
- A static initialiser block runs once, when the class is initialised, and is where you initialise a static collection that must not be a mutable constant.
public class Catalog {
public static final int MAX_ITEMS = 500;
private static final Map<String, MediaItem> INDEX = new HashMap<>();
static {
INDEX.put("SKU-1001", new Book("SKU-1001", "The Pragmatic Programmer", 352));
}
public static MediaItem find(String sku) {
return INDEX.get(sku);
}
}
The collections framework lives in java.util and gives you three main abstractions.
List<String> names = new ArrayList<>(); // ordered, duplicates allowed
Set<Integer> skus = new LinkedHashSet<>(); // unique, insertion ordered
Map<String, Integer> stock = new HashMap<>(); // unique keys, lookup by key
ArrayList and HashMap are the defaults for almost all code. Reach for LinkedHashMap when the iteration order must follow insertion order, and for TreeMap or TreeSet when the keys must be sorted and you want the log n lookups that come with it. List.of and Map.of create immutable collections, and Collections.unmodifiableList wraps an existing list in a read-only view.
List<String> names = List.of("Ada", "Grace", "Alan");
Map<String, Integer> counts = new HashMap<>();
counts.put("book", 3);
counts.put("dvd", 1);
counts.computeIfAbsent("audiobook", key -> 0);
counts.forEach((key, value) -> System.out.printf("%s: %d%n", key, value));
List<String> sorted = new ArrayList<>(names);
sorted.sort(Comparator.comparing(String::length));
List<String> longEnough = sorted.stream()
.filter(name -> name.length() >= 4)
.toList();
The streams API is built on the collections, not instead of them, and toList() returns an unmodifiable list.
| Mistake | What actually happens | Correction |
|---|---|---|
Overriding equals but not hashCode | HashSet and HashMap treat equal objects as different | Override both, or neither |
Making a static method and expecting it to be overridden | The method is hidden, and the reference type decides which runs | Use an instance method if you need dynamic dispatch |
Calling super(...) after another statement | Compile error, the call must come first | Move the super call to the top of the constructor |
| Assuming a default constructor still exists | It disappears as soon as any constructor is declared | Declare an explicit no-argument constructor if you need one |
| Forgetting that the default access is package-private | Code in another package cannot see the type | Mark the type or member public |
Putting a mutable field into equals and hashCode | The object changes its hash bucket after being stored | Base both methods on immutable fields only |
Using == to compare strings | It compares references, not content | Use equals, or compare interned constants with == |
| Casting to a parameterised generic type | The cast is unchecked and can fail at runtime | Use a wildcard or an unchecked cast with a warning |
Closing a Scanner built on System.in | Standard input is closed for the whole process | Do not close it |
With the object model in place, the next stage of a Java project is the collection framework in earnest, and then the concurrency and tooling layers that build on top of it.
Approach:
Object-oriented design in Java comes down to a small number of decisions that the language lets you express directly: what state a type owns, who may see it, how it may be extended, and how its instances are compared. The approach here is to make each of those decisions explicit in code. A type is either a class with behaviour and identity, or a record for pure data, or an enum for a closed set of constants. Extension is either open, with extends and interfaces, or closed, with sealed. Equality is either identity, the default from Object, or value equality, which requires overriding equals and hashCode together.
Steps:
- Declare the state as
privatefields, expose it through methods that validate their inputs, and mark the fields that identify the object asfinal. - Write the constructors so that they chain with
this(...), so that a single constructor assembles the fully initialised object and the others cannot drift. - Choose the visibility deliberately for each member:
privateby default,protectedonly when a subclass genuinely needs it, andpubliconly for the API surface. - Design the hierarchy around the shared abstraction. Use an abstract class when the subtypes share state and implementation, an interface when they share only behaviour, and a
defaultmethod when there is a sensible shared implementation that subclasses may override. - Add
@Overrideto every overriding method, and remember thatstaticmethods are hidden rather than overridden, which is the usual reason a “polymorphic” call surprises people. - For data-only types, write a
recordwith a compact constructor for validation, and for a closed set of constants write anenumwith its own fields and constructor. - When the set of permitted implementations must be known at compile time, seal the type with
sealedandpermits, which also makesswitchover it exhaustive. - Implement value equality by overriding
equalsandhashCodetogether, based only on immutable fields, and useObjects.equalsandObjects.hashto stay null-safe. - Put collections behind the
List,SetandMapinterfaces, choose the concrete implementation for its iteration order, and use the unmodifiable factories when the collection should not change.
Answer:
After this chapter the object model of a Java project looks like this:
- A domain type such as
MediaItemis an ordinary class whose fields areprivate, whose accessors are named methods, and whose identity field isfinal. - A data carrier such as
CartLineis arecord, whose accessors are named after the components, whose equality is generated, and whose validation lives in a compact constructor. - A closed set of constants such as
MediaTypeis anenum, whose constants are singletons that can be compared with==and switched on exhaustively. - A closed hierarchy such as
Notificationissealedandpermitsexactly the implementations it supports, so aswitchover it is checked by the compiler. - Shared behaviour is expressed in an interface with
defaultmethods, shared state and implementation in an abstract class, and dynamic dispatch happens for overridden instance methods only. - Value equality is implemented by overriding
equalsandhashCodetogether from immutable fields, which keepsHashMapandHashSetcorrect. - Collections are held as
List,SetandMap, withArrayList,HashMap,LinkedHashMapandTreeMapchosen for the required iteration order.
A reviewer reading that code can now tell, from the declarations alone, which types carry behaviour, which carry data, which hierarchies are closed, and which equality contract each class honours.
