Java NotesRohit’s interview study guide
Chapter 03

Classes, Objects, Records and Enums

How Java classes compare with TypeScript classes, access levels including package-private, static and final, inheritance and the difference between overloading and overriding, interfaces and nominal typing, the equals/hashCode contract, records, enums, sealed types, and the four kinds of nested class. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1).

Try it yourself. As in chapter 01: for each example, make an empty folder, save every code box in it under the name in its caption (com/example/bank/Account.java means a com/example/bank folder), and type the $ lines of the Terminal box there. Examples about classes use the classic public class Main with public static void main, because that's what real projects look like; several classes can share one file as long as only the first is public. A run that ends in an exception or a compiler error is shown on purpose; the text says so.

10 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Classes, constructors and access modifiers

Added

A Java class will look familiar from TypeScript: fields, a constructor, methods, this, private. TypeScript borrowed much of its class syntax from Java and C#. The differences are in the details, and they matter:

  • Fields are declared with their types in the class body, and every field has a default (0, false, null) until a constructor sets it. There are no parameter properties (constructor(private name: string)); you assign this.name = name yourself.
  • The constructor is named after the class, and a class can have several constructors with different parameters (overloading). One constructor can call another with this(...). TypeScript has one constructor and optional parameters instead.
  • Access modifiers are enforced by the compiler and the JVM. TypeScript's private disappears when the code is compiled to JavaScript (only #private survives at run time). Java's private is still there in the bytecode, and the JVM refuses access from other classes.
  • There are four access levels, not three. Leaving the modifier off doesn't mean public: it means package-private, visible only to classes in the same package.
ModifierSame classSame packageSubclass in another packageEverywhere
privateyesnonono
(none): package-privateyesyesnono
protectedyesyesyesno
publicyesyesyesyes

The mental model: a package is a team, and package-private is "internal to the team". Classes in the same package cooperate freely; everyone else sees only what you mark public. That's why well-organised Java code keeps most helper classes package-private and exposes a small public surface, the way a Node package exposes only what its index.js exports.

com/example/bank/Account.java
package com.example.bank;

public class Account {
    private final String owner;
    private long balanceInCents;
    String branch = "Leeds";                 // no modifier: package-private

    public Account(String owner) {
        this(owner, 0);                      // calls the other constructor
    }

    public Account(String owner, long openingCents) {
        if (openingCents < 0) {
            throw new IllegalArgumentException("opening balance can't be negative");
        }
        this.owner = owner;
        this.balanceInCents = openingCents;
    }

    public void deposit(long cents) {
        if (cents <= 0) {
            throw new IllegalArgumentException("deposit must be positive");
        }
        balanceInCents += cents;
    }

    public long balance() {
        return balanceInCents;
    }

    public String owner() {
        return owner;
    }
}
com/example/bank/Audit.java
package com.example.bank;

public class Audit {
    public static String describe(Account account) {
        return account.owner() + " banks at " + account.branch;   // same package: allowed
    }
}
com/example/app/Main.java
package com.example.app;

import com.example.bank.Account;
import com.example.bank.Audit;

public class Main {
    public static void main(String[] args) {
        var account = new Account("Rohit", 10_000);
        account.deposit(2_550);
        System.out.println(account.owner() + ": " + account.balance() + " cents");
        System.out.println(Audit.describe(account));

        var empty = new Account("Maya");
        System.out.println(empty.owner() + ": " + empty.balance() + " cents");
    }
}
Terminal
$ javac -d out com/example/bank/Account.java com/example/bank/Audit.java com/example/app/Main.java
$ java -cp out com.example.app.Main
Rohit: 12550 cents
Rohit banks at Leeds
Maya: 0 cents
What’s happening
  1. Account has two constructors. new Account("Rohit", 10_000) picks the two-argument one by its parameter types; it validates the opening balance and sets both fields. (10_000 is just 10000: underscores in number literals are allowed since Java 7.)
  2. new Account("Maya") picks the one-argument constructor, which immediately calls this(owner, 0), so the validation lives in one place. The balance prints as 0 cents.
  3. owner is private final: set once in the constructor and readable only through the owner() method. balanceInCents is private and only changes through deposit, which refuses non-positive amounts. That's encapsulation: the class guarantees its own rules.
  4. deposit(2_550) takes the balance from 10,000 to 12,550, printed as Rohit: 12550 cents.
  5. branch has no modifier, so it's package-private. Audit is in the same package, com.example.bank, so it can read account.branch directly: Rohit banks at Leeds. Main, in com.example.app, can't (see the next example).
  6. The accessors are named owner() and balance(), the style records use. Older code and many frameworks use the JavaBeans style, getOwner() and getBalance(); you'll see both, and many codebases generate them with the Lombok library.
AdvancedWhat the compiler says from outside the package
com/example/app/Snoop.java
package com.example.app;

import com.example.bank.Account;

public class Snoop {
    public static void main(String[] args) {
        var account = new Account("Rohit");
        System.out.println(account.branch);
        account.balanceInCents = 1_000_000;
    }
}
Terminal
$ javac -cp out -d out com/example/app/Snoop.java
com/example/app/Snoop.java:8: error: branch is not public in Account; cannot be accessed from outside package
        System.out.println(account.branch);
                                  ^
com/example/app/Snoop.java:9: error: balanceInCents has private access in Account
        account.balanceInCents = 1_000_000;
               ^
2 errors
What’s happening
  1. Snoop lives in com.example.app, so it's outside Account's package. It's compiled against the classes already in out (-cp out).
  2. Reading account.branch fails: package-private means invisible outside com.example.bank, and the message says exactly that.
  3. Writing account.balanceInCents fails too: it's private to Account.
  4. Both errors are compile-time, and nothing is produced. In TypeScript, private gives the same kind of error, but (account as any).balanceInCents = 1_000_000 would get through and work at run time. In Java there's no such cast that gets around the check; only reflection (setAccessible) can reach private members, and that's a deliberate, visible act.

#static and final

Added

static means "belongs to the class, not to each object". A static field exists once, however many objects you create (and even if you create none); a static method is called on the class (Math.max(a, b)) and has no this. TypeScript's static is the same idea. In Node terms, a static field is like a variable at the top level of a module: one copy, shared by everyone who imports it.

final means "assigned once". A final local variable or field can't be reassigned, which is JavaScript's const, with the same catch: the variable is fixed, not the object it points to. A final List can still have items added. final also has two other meanings, on classes (can't be extended) and methods (can't be overridden).

Put together, static final is how Java spells a constant: static final int MAX_PER_ORDER = 4;, named in UPPER_SNAKE_CASE.

The mental model: instance fields are written on each ticket; static fields are written on the ticket machine. Every ticket has its own number, but there's one counter inside the machine.

Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var keynote = new Ticket("Keynote");
        var workshop = new Ticket("Workshop");
        System.out.println(keynote + ", " + workshop + ", issued " + Ticket.issued());
        System.out.println("max per order: " + Ticket.MAX_PER_ORDER);

        final List<String> names = new ArrayList<>();
        names.add("Rohit");
        System.out.println(names);
    }
}

class Ticket {
    static final int MAX_PER_ORDER = 4;
    private static int nextNumber = 1;

    private final int number;
    private final String event;

    Ticket(String event) {
        this.event = event;
        this.number = nextNumber++;
    }

    static int issued() {
        return nextNumber - 1;
    }

    @Override
    public String toString() {
        return "#" + number + " " + event;
    }
}
Terminal
$ java Main.java
#1 Keynote, #2 Workshop, issued 2
max per order: 4
[Rohit]
What’s happening
  1. nextNumber is static, so there's one copy for the whole Ticket class, starting at 1. number and event are instance fields: every Ticket has its own.
  2. The first constructor call stores number = 1 and moves nextNumber to 2 (nextNumber++ returns the old value, then adds one). The second stores 2 and moves it to 3.
  3. Ticket.issued() is a static method, called on the class. It can read nextNumber but not number: there's no this in a static method, so "which ticket's number?" has no answer. It returns 3 - 1 = 2.
  4. toString() is called automatically when a ticket is joined to a string, so the line prints #1 Keynote, #2 Workshop, issued 2. MAX_PER_ORDER is a constant, read through the class name: 4.
  5. names is final, yet names.add("Rohit") works and prints [Rohit]. final fixes the reference; the list itself is still mutable. names = new ArrayList<>() would be a compile error.
  6. number and event are private final: set in the constructor, never changed. A class whose fields are all final and whose objects never change is immutable; see below.
AdvancedWhat final and static forbid
Rules.java
public class Rules {
    private final int limit = 10;
    private int count;

    void reset() {
        limit = 20;
    }

    static void show() {
        System.out.println(count);
    }

    public static void main(String[] args) {
        final int answer = 42;
        answer = 43;
    }
}
Terminal
$ java Rules.java
Rules.java:6: error: cannot assign a value to final variable limit
        limit = 20;
        ^
Rules.java:10: error: non-static variable count cannot be referenced from a static context
        System.out.println(count);
                           ^
Rules.java:15: error: cannot assign a value to final variable answer
        answer = 43;
        ^
3 errors
error: compilation failed
What’s happening
  1. limit = 20 reassigns a final field after construction, which the compiler refuses.
  2. show() is static and reads count, an instance field. With no object, there's no count to read: the message is the famous "non-static variable count cannot be referenced from a static context", which every Java beginner meets when they call instance code from main.
  3. answer = 43 reassigns a final local variable.
  4. Three errors, nothing runs. The fix for the second is either to make show an instance method or to pass it an object: static void show(Rules r) { System.out.println(r.count); }.
AdvancedAn immutable class

An immutable class needs more than final fields: if a field holds a mutable object such as a List, the class must also stop anyone else from holding a reference to that list. The usual recipe: a final class (no subclass can add mutable state), private final fields, no setters, and defensive copies of anything mutable that comes in.

Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var items = new ArrayList<>(List.of("keyboard"));
        var leaky = new LeakyOrder(items);
        var safe = new SafeOrder(items);

        items.add("mouse");
        System.out.println("leaky: " + leaky.items());
        System.out.println("safe:  " + safe.items());

        try {
            safe.items().add("monitor");
        } catch (UnsupportedOperationException e) {
            System.out.println("safe.items().add: " + e);
        }
    }
}

final class LeakyOrder {
    private final List<String> items;

    LeakyOrder(List<String> items) {
        this.items = items;
    }

    List<String> items() {
        return items;
    }
}

final class SafeOrder {
    private final List<String> items;

    SafeOrder(List<String> items) {
        this.items = List.copyOf(items);
    }

    List<String> items() {
        return items;
    }
}
Terminal
$ java Main.java
leaky: [keyboard, mouse]
safe:  [keyboard]
safe.items().add: java.lang.UnsupportedOperationException
What’s happening
  1. Both orders get the same caller's list, [keyboard], and both store it in a private final field.
  2. LeakyOrder keeps the caller's list itself. When the caller later adds mouse, the order changes too: leaky: [keyboard, mouse]. final didn't help, because the list was never the order's alone.
  3. SafeOrder stores List.copyOf(items) (Java 10), an unmodifiable copy. The caller's later change doesn't reach it: safe: [keyboard].
  4. And because the copy is unmodifiable, it can be handed out from items() safely: trying to add to it throws UnsupportedOperationException.
  5. Immutable objects are simple to reason about and safe to share between threads, which matters in a Spring app where one service object serves every request. Records (below) do most of this recipe for you, except the defensive copy.

#Inheritance and polymorphism

Added

A class can extend one other class (class EmailNotification extends Notification), inheriting its fields and methods, and it can override methods to change their behaviour. Every class that doesn't say extends extends Object. A class marked abstract can't be instantiated and can declare abstract methods with no body, which every concrete subclass must implement. This works like TypeScript's extends and abstract.

Polymorphism is the payoff: code that holds a Notification reference calls deliver() and gets the right subclass's behaviour, chosen at run time by the object's actual class. That's dynamic dispatch, and it's what JavaScript does too through the prototype chain.

What Java adds, and TypeScript doesn't have, is overloading: several methods with the same name and different parameter types. The two are easy to confuse and interviewers love the difference:

  • Overriding = same signature in a subclass; chosen at run time by the object's class.
  • Overloading = same name, different parameters; chosen at compile time by the declared types of the arguments.

The mental model: overriding asks the object "what are you?"; overloading asks the compiler "what does the code say it is?"

Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Notification> outbox = List.of(
                new EmailNotification("ana@example.com", "Order shipped"),
                new SmsNotification("+44 7700 900123", "Your code is 4821"));

        for (Notification n : outbox) {
            System.out.println(n.deliver());
        }
    }
}

abstract class Notification {
    protected final String message;

    Notification(String message) {
        this.message = message;
    }

    final String deliver() {                 // the same steps for every kind
        return "[" + channel() + "] " + format();
    }

    abstract String channel();               // every subclass must say which

    String format() {                        // a default subclasses may replace
        return message;
    }
}

class EmailNotification extends Notification {
    private final String address;

    EmailNotification(String address, String message) {
        super(message);
        this.address = address;
    }

    @Override
    String channel() {
        return "email";
    }

    @Override
    String format() {
        return "To: " + address + " | " + super.format();
    }
}

class SmsNotification extends Notification {
    private final String number;

    SmsNotification(String number, String message) {
        super(message.length() > 12 ? message.substring(0, 12) + "..." : message);
        this.number = number;
    }

    @Override
    String channel() {
        return "sms";
    }

    @Override
    String format() {
        return number + ": " + message;
    }
}
Terminal
$ java Main.java
[email] To: ana@example.com | Order shipped
[sms] +44 7700 900123: Your code is...
What’s happening
  1. outbox is a List<Notification>: the loop only knows it has Notifications. Notification is abstract, so new Notification(...) wouldn't compile; only the subclasses can be created.
  2. deliver() is final, so every subclass uses exactly these steps (a template method). It calls channel() and format(), and dynamic dispatch picks each object's own version at run time.
  3. For the email, channel() is "email" and format() builds To: ana@example.com | and then calls super.format(), the parent's version, which returns the message. Result: [email] To: ana@example.com | Order shipped.
  4. The SMS constructor shortens the message before passing it up with super(...): the expression in the call runs first, so the parent stores Your code is.... Its format() uses the inherited protected field message: [sms] +44 7700 900123: Your code is....
  5. @Override asks the compiler to check that the method really overrides something. It's optional, but without it a typo creates a new method silently (see the gotcha below).
  6. Java has single inheritance of classes: EmailNotification can extend only Notification. To share behaviour across unrelated classes, use interfaces (next topic) or composition.
Overloaded or overridden?
Main.java
public class Main {
    static String describe(Object o) {
        return "object";
    }

    static String describe(String s) {
        return "string";
    }

    public static void main(String[] args) {
        Object thing = "hello";
        System.out.println(describe(thing));
        System.out.println(describe("hello"));

        Animal pet = new Dog();
        System.out.println(pet.sound());
    }
}

class Animal {
    String sound() {
        return "...";
    }
}

class Dog extends Animal {
    @Override
    String sound() {
        return "woof";
    }
}
Show answer
Terminal
$ java Main.java
object
string
woof
What’s happening
  1. describe is overloaded. The compiler picks the overload from the argument's declared type. thing is declared Object, so describe(thing) calls describe(Object) and prints object, even though the object is a String at run time.
  2. describe("hello") passes an expression whose type is String, so the more specific describe(String) wins: string.
  3. sound() is overridden. pet is declared Animal, but the call is dispatched on the object, a Dog, so it prints woof.
  4. So the same "declared as the parent type" setup gives opposite answers. Overloads are resolved at compile time from static types; overrides at run time from the object.
AdvancedCalling an overridable method from a constructor

A constructor runs its parent's constructor first. If the parent constructor calls a method that the subclass overrides, the subclass's version runs before the subclass's own fields are set. Effective Java has a rule against it ("constructors must not invoke overridable methods"), and JEP 513 uses this exact bug to motivate flexible constructor bodies (Java 25): you may now put statements before super(...), as long as they don't use this other than to assign fields.

Main.java
public class Main {
    public static void main(String[] args) {
        new Employee("Maya", "CAM-1");
        new Contractor("Ana", "LDN-2");
    }
}

class Person {
    final String name;

    Person(String name) {
        this.name = name;
        show();                         // runs the subclass's version
    }

    void show() {
        System.out.println("Person " + name);
    }
}

class Employee extends Person {
    final String office;

    Employee(String name, String office) {
        super(name);
        this.office = office;
    }

    @Override
    void show() {
        System.out.println("Employee " + name + " at " + office);
    }
}

class Contractor extends Person {
    final String office;

    Contractor(String name, String office) {
        this.office = office;           // Java 25: allowed before super(...)
        super(name);
    }

    @Override
    void show() {
        System.out.println("Contractor " + name + " at " + office);
    }
}
Terminal
$ java Main.java
Employee Maya at null
Contractor Ana at LDN-2
$ javac --release 21 Main.java
Main.java:39: error: flexible constructors is not supported in -source 21
        this.office = office;           // Java 25: allowed before super(...)
        ^
  (use -source 25 or higher to enable flexible constructors)
1 error
What’s happening
  1. new Employee("Maya", "CAM-1") first runs super(name), the Person constructor. It sets name and calls show().
  2. The object is an Employee, so dynamic dispatch runs Employee.show(), but Employee's constructor hasn't got past super(name) yet, so office still has its default value: Employee Maya at null. A final field has been seen before it was assigned.
  3. Contractor assigns this.office before calling super(name). Before Java 25 that wasn't allowed, as the last command shows: compiling for Java 21 fails with "flexible constructors is not supported in -source 21". On Java 25 the constructor has a prologue (before super) and an epilogue (after).
  4. So when Person's constructor calls show(), the field is already set: Contractor Ana at LDN-2.
  5. The prologue is also the natural place to validate arguments before the parent does any work. The safer habit is still not to call overridable methods from constructors at all; Java 25 just gives you a way out when a superclass you don't control does it.
Advanced@Override catches typos
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(new Product("Desk"));
    }
}

class Product {
    private final String name;

    Product(String name) {
        this.name = name;
    }

    @Override
    public String tostring() {
        return "Product " + name;
    }
}
Terminal
$ java Main.java
Main.java:14: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error
error: compilation failed
What’s happening
  1. The method is meant to override Object.toString(), but it's spelled tostring. Without @Override that's a legal new method, and printing the product would quietly use Object's default toString.
  2. With @Override, the compiler checks that some supertype has this method, finds none, and fails with "method does not override or implement a method from a supertype".
  3. Always write @Override; IDEs add it for you. It also catches a subtler mistake: overloading when you meant to override, as in equals(Product other) instead of equals(Object other) (see equals, hashCode and toString).

#Interfaces

Added

An interface is a contract: a list of methods a class promises to provide. A class can implement any number of interfaces, and code that depends on the interface (PaymentGateway) doesn't care which class is behind it, which is the basis of dependency injection in Spring (chapter 12).

Since your Java 6 days, interfaces have grown. Java 8 added default methods (a method with a body that implementing classes inherit, and may override) and static methods (helpers called on the interface itself). Java 9 added private methods, so default methods can share code without exposing it. An interface still can't have instance fields: its fields are constants (public static final).

The big difference from TypeScript is nominal typing. In TypeScript, a class or object literal fits an interface if it has the right shape; it never needs to mention the interface. In Java, a class implements an interface only if it says implements. Having the right methods isn't enough. That's less flexible (you can't make a library class "fit" an interface after the fact without wrapping it), but it means implementing an interface is a deliberate, searchable decision, and renaming a method in the interface breaks every implementation at compile time.

The mental model: a TypeScript interface is a shape test; a Java interface is a signed contract. Matching the shape isn't signing.

Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Shipper> shippers = List.of(new Courier(), new PostOffice(), Shipper.cheapest());
        for (Shipper s : shippers) {
            System.out.println(s.name() + ": " + s.quote(2.5) + " | " + s.track("PX-1"));
        }

        var courier = new Courier();
        System.out.println(courier.cover() + ", is a Shipper: " + (courier instanceof Shipper));
    }
}

interface Shipper {
    String name();
    double quote(double kg);                // abstract: implementers must provide it

    default String track(String id) {        // Java 8: inherited unless overridden
        return "track " + id + " at " + url();
    }

    private String url() {                   // Java 9: a helper for the defaults
        return "https://track.example/" + name().toLowerCase();
    }

    static Shipper cheapest() {              // Java 8: called as Shipper.cheapest()
        return new PostOffice();
    }
}

interface Insured {
    default String cover() {
        return "insured up to 500";
    }
}

class Courier implements Shipper, Insured {
    public String name() {
        return "Courier";
    }

    public double quote(double kg) {
        return 5 + kg * 2;
    }
}

class PostOffice implements Shipper {
    public String name() {
        return "Post";
    }

    public double quote(double kg) {
        return 3 + kg;
    }

    @Override
    public String track(String id) {
        return "ask at the counter for " + id;
    }
}
Terminal
$ java Main.java
Courier: 10.0 | track PX-1 at https://track.example/courier
Post: 5.5 | ask at the counter for PX-1
Post: 5.5 | ask at the counter for PX-1
insured up to 500, is a Shipper: true
What’s happening
  1. Shipper declares two abstract methods, name() and quote(double). Interface methods are public by default, so the classes must implement them as public (leaving public off is a compile error: "attempting to assign weaker access privileges").
  2. Courier doesn't write track, so it inherits the default method, which calls the private url(): track PX-1 at https://track.example/courier. Its quote is 5 + 2.5 × 2 = 10.0.
  3. PostOffice overrides the default track with its own: ask at the counter for PX-1. Its quote is 3 + 2.5 = 5.5.
  4. Shipper.cheapest() is a static interface method, called on the interface name. It returns another PostOffice, so the third line repeats the Post one.
  5. Courier implements two interfaces and gets cover() from Insured. instanceof Shipper is true because the class declared implements Shipper. A class can implement many interfaces but extend only one class.
AdvancedNominal typing: the right methods aren't enough
Structural.java
public class Structural {
    public static void main(String[] args) {
        Greeter greeter = new Robot();
        System.out.println(greeter.greet());
    }
}

interface Greeter {
    String greet();
}

class Robot {                         // has greet(), but never says "implements Greeter"
    public String greet() {
        return "beep";
    }
}
Terminal
$ java Structural.java
Structural.java:3: error: incompatible types: Robot cannot be converted to Greeter
        Greeter greeter = new Robot();
                          ^
1 error
error: compilation failed
What’s happening
  1. Robot has exactly the method Greeter asks for. In TypeScript, const greeter: Greeter = new Robot() would compile: the shapes match.
  2. Java refuses: "incompatible types: Robot cannot be converted to Greeter". The compiler only accepts a Robot as a Greeter if Robot declares implements Greeter (or extends a class that does).
  3. The fix is one word, class Robot implements Greeter. When you can't change the class (it's in a library), you wrap it in an adapter, or, when the interface has a single method, pass a lambda or method reference: Greeter greeter = robot::greet; works, because a lambda can implement any functional interface (chapter 08).
AdvancedWhen two defaults clash

Default methods bring back a small version of the multiple-inheritance "diamond" problem: if two interfaces give a class the same default method, Java won't guess. The class must override it, and it can call either parent with Interface.super.method().

Clash.java
public class Clash {
    public static void main(String[] args) {
        System.out.println(new Phone().describe());
    }
}

interface Camera {
    default String describe() {
        return "takes photos";
    }
}

interface MusicPlayer {
    default String describe() {
        return "plays music";
    }
}

class Phone implements Camera, MusicPlayer {
}
Fixed.java
public class Fixed {
    public static void main(String[] args) {
        System.out.println(new Phone().describe());
    }
}

interface Camera {
    default String describe() {
        return "takes photos";
    }
}

interface MusicPlayer {
    default String describe() {
        return "plays music";
    }
}

class Phone implements Camera, MusicPlayer {
    @Override
    public String describe() {
        return Camera.super.describe() + " and " + MusicPlayer.super.describe();
    }
}
Terminal
$ java Clash.java
Clash.java:19: error: types Camera and MusicPlayer are incompatible;
class Phone implements Camera, MusicPlayer {
^
  class Phone inherits unrelated defaults for describe() from types Camera and MusicPlayer
1 error
error: compilation failed
$ java Fixed.java
takes photos and plays music
What’s happening
  1. In Clash.java, Phone inherits describe() from both Camera and MusicPlayer, and neither is more specific. The compiler reports that Phone inherits unrelated defaults for describe() from both types, and nothing runs.
  2. In Fixed.java, Phone overrides describe(). Camera.super.describe() calls Camera's default and MusicPlayer.super.describe() the other: takes photos and plays music.
  3. A rule that settles most other cases: a class method always beats an interface default. If Phone extended a class that had describe(), that would win with no error.
AdvancedFunctional interfaces, a preview

An interface with exactly one abstract method is a functional interface, and a lambda can implement it. That's how Java 8 added lambdas without adding function types: Comparator, Runnable and Function are all just interfaces. Chapter 08 covers them properly; here's the shape:

Rules.java
import java.util.List;

public class Rules {
    public static void main(String[] args) {
        PriceRule tenPercentOff = price -> price * 0.9;
        PriceRule minusFive = price -> Math.max(0, price - 5);

        double price = 40;
        for (PriceRule rule : List.of(tenPercentOff, minusFive)) {
            price = rule.apply(price);
        }
        System.out.println("final price: " + price);
    }
}

@FunctionalInterface
interface PriceRule {
    double apply(double price);
}
Terminal
$ java Rules.java
final price: 31.0
What’s happening
  1. PriceRule has one abstract method, so a lambda price -> price * 0.9 is an implementation of it: the compiler turns the lambda into an object whose apply runs that expression.
  2. @FunctionalInterface is optional; it makes the compiler check that the interface keeps exactly one abstract method.
  3. The loop applies both rules in order: 40 → 36.0 → 31.0, printed as final price: 31.0.
  4. In TypeScript you'd write type PriceRule = (price: number) => number. Java has no function types, so it names the "shape" with an interface instead.

#equals, hashCode and toString

Added

Every class inherits three methods from Object that you'll override constantly:

  • toString(): the text shown when you print the object. Object's version prints the class name, @ and a hash code in hex, which is useless in a log.
  • equals(Object): whether two objects are "the same value". Object's version is ==: the same object or nothing. JavaScript has no equivalent at all: { id: 1 } === { id: 1 } is false, and there's no method a Set or Map will call to ask otherwise.
  • hashCode(): a number derived from the object, used by HashMap and HashSet to pick a bucket. Object's version is based on the object's identity.

The contract that ties them together: if two objects are equals, they must have the same hashCode. (The reverse isn't required: different objects may share a hash code.) Equality must also be reflexive, symmetric, transitive and consistent, and x.equals(null) must be false.

The mental model: a HashSet is a wall of numbered pigeonholes. To find an object it first computes hashCode() to pick the pigeonhole, and only then uses equals to compare with what's inside. Override equals without hashCode, and two "equal" objects go into different pigeonholes, so the set never even compares them.

Main.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<PlainPoint> plain = new HashSet<>();
        plain.add(new PlainPoint(1, 2));
        plain.add(new PlainPoint(1, 2));
        System.out.println("neither:     size " + plain.size() + ", contains " + plain.contains(new PlainPoint(1, 2)));

        Set<HalfPoint> half = new HashSet<>();
        half.add(new HalfPoint(1, 2));
        System.out.println("equals only: equals " + new HalfPoint(1, 2).equals(new HalfPoint(1, 2))
                + ", contains " + half.contains(new HalfPoint(1, 2)));

        Set<Point> good = new HashSet<>();
        good.add(new Point(1, 2));
        good.add(new Point(1, 2));
        System.out.println("both:        size " + good.size() + ", contains " + good.contains(new Point(1, 2)));

        System.out.println(new Point(1, 2));
        System.out.println(new PlainPoint(1, 2).toString().replaceAll("@\\p{XDigit}+", "@<hash>"));
    }
}

class PlainPoint {
    final int x, y;
    PlainPoint(int x, int y) { this.x = x; this.y = y; }
}

class HalfPoint {
    final int x, y;
    HalfPoint(int x, int y) { this.x = x; this.y = y; }

    @Override
    public boolean equals(Object o) {
        return o instanceof HalfPoint p && x == p.x && y == p.y;
    }
}

class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Point p && x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }

    @Override
    public String toString() {
        return "Point(" + x + ", " + y + ")";
    }
}
Terminal
$ java Main.java
neither:     size 2, contains false
equals only: equals true, contains false
both:        size 1, contains true
Point(1, 2)
PlainPoint@<hash>
What’s happening
  1. PlainPoint overrides nothing, so equality is identity. The two new PlainPoint(1, 2) objects are different objects, the set keeps both (size 2), and a third new one isn't "contained".
  2. HalfPoint overrides equals (using a type pattern, o instanceof HalfPoint p, Java 16; see chapter 05), so equals says true. But hashCode is still identity-based, so the lookup computes a different hash, looks in a different pigeonhole and never calls equals: contains false. (In theory two identity hash codes could match by chance; in practice they don't.) This is the bug the contract prevents.
  3. Point overrides both. Objects.hash(x, y) combines the fields into one number, the same for equal points, so the second add finds the first and is ignored (size 1), and contains is true.
  4. Point's toString prints Point(1, 2). PlainPoint uses Object.toString(): the class name, @ and the identity hash in hex. The hash changes every run, so the program replaces it with <hash> here.
  5. Use the same fields in equals and hashCode, and prefer fields that never change. For a plain data class, a record (next topic) writes all three methods for you.
equals that doesn't override
Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var a = new Sku("A-1");
        var b = new Sku("A-1");
        System.out.println(a.equals(b));
        System.out.println(List.of(a).contains(b));
    }
}

class Sku {
    final String code;

    Sku(String code) {
        this.code = code;
    }

    public boolean equals(Sku other) {
        return code.equals(other.code);
    }

    @Override
    public int hashCode() {
        return code.hashCode();
    }
}
Show answer
Terminal
$ java Main.java
true
false
What’s happening
  1. equals(Sku other) doesn't override Object.equals(Object): the parameter type differs, so it's an overload, a new method that happens to share the name.
  2. a.equals(b) is called with a Sku argument, so the compiler picks the more specific overload, equals(Sku): codes match, true.
  3. List.contains was written long before Sku and calls equals(Object). That's still Object's identity check, so it's false.
  4. The same object gives two different answers to "are these equal?". Writing @Override on the method would have turned this into a compile error, and the fix is the signature public boolean equals(Object o).
AdvancedMutable keys break hash collections

The pigeonhole is chosen when the object is added. Change a field that hashCode uses afterwards, and the object sits in the wrong pigeonhole: the set can no longer find it, even though it's still inside.

Main.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<Tag> tags = new HashSet<>();
        var tag = new Tag("java");
        tags.add(tag);

        tag.name = "JAVA";
        System.out.println("contains: " + tags.contains(tag));
        System.out.println("remove: " + tags.remove(tag));
        System.out.println("size: " + tags.size() + ", " + tags);
    }
}

class Tag {
    String name;

    Tag(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Tag t && name.equals(t.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public String toString() {
        return name;
    }
}
Terminal
$ java Main.java
contains: false
remove: false
size: 1, [JAVA]
What’s happening
  1. tags.add(tag) computes the hash of "java" and stores the tag in that pigeonhole.
  2. tag.name = "JAVA" changes the field that hashCode uses. The set isn't told; the tag stays where it was.
  3. contains(tag) computes the hash of "JAVA", a different pigeonhole, finds nothing: false. remove(tag) fails the same way: false.
  4. But iterating still finds it: size: 1, [JAVA]. The set now holds an object it can't find or remove, which in a long-running service is a memory leak. Keys of a HashMap and elements of a HashSet should be immutable, which is another reason to use records or strings as keys.

#Records

Added

A record (Java 16) is a class whose whole job is to carry data. You list its components in the header, record Product(String sku, String name, BigDecimal price) {}, and the compiler writes the rest: a private final field for each component, a constructor that takes them all (the canonical constructor), an accessor for each (sku(), not getSku()), and equals, hashCode and toString based on all the components. It's what you'd write by hand as an immutable class in thirty lines, or with Lombok's @Value, in one.

Records have rules that keep them honest: a record is implicitly final (no subclasses), can't extend another class (it extends java.lang.Record), and can't declare instance fields beyond its components. It can implement interfaces, and have static fields, static and instance methods, and extra constructors. To validate or normalise the inputs, you write a compact constructor: the constructor without a parameter list, which runs before the fields are assigned.

For a TypeScript developer, the nearest thing is type Product = { readonly sku: string; ... }, but with one big difference: records have value equality. Two records with the same components are equals and have the same hashCode, so they work as map keys and set elements, which plain JavaScript objects never do.

The mental model: a record is a named, typed, immutable tuple that knows how to compare and print itself.

Products.java
record Product(String sku, String name, BigDecimal price) {
    Product {                                   // compact constructor
        Objects.requireNonNull(sku, "sku");
        if (price.signum() < 0) {
            throw new IllegalArgumentException("price can't be negative: " + price);
        }
        name = name.strip();                    // normalise before the field is set
    }

    Product withPrice(BigDecimal newPrice) {
        return new Product(sku, name, newPrice);
    }
}

void main() {
    var desk = new Product("D-1", "  Standing desk ", new BigDecimal("299.00"));
    IO.println(desk);
    IO.println(desk.name() + " costs " + desk.price());

    var same = new Product("D-1", "Standing desk", new BigDecimal("299.00"));
    IO.println("equals: " + desk.equals(same) + ", same hashCode: " + (desk.hashCode() == same.hashCode()));
    IO.println("in a set: " + new HashSet<>(List.of(desk, same)).size());

    var sale = desk.withPrice(new BigDecimal("249.00"));
    IO.println(sale + ", original still " + desk.price());

    try {
        new Product("D-2", "Chair", new BigDecimal("-1"));
    } catch (IllegalArgumentException e) {
        IO.println("rejected: " + e.getMessage());
    }
}
Terminal
$ java Products.java
Product[sku=D-1, name=Standing desk, price=299.00]
Standing desk costs 299.00
equals: true, same hashCode: true
in a set: 1
Product[sku=D-1, name=Standing desk, price=249.00], original still 299.00
rejected: price can't be negative: -1
What’s happening
  1. The header (String sku, String name, BigDecimal price) gives Product three private final fields, a canonical constructor, the accessors sku(), name() and price(), and equals, hashCode and toString.
  2. The compact constructor Product { … } runs with the constructor's parameters in scope, before the fields are assigned. It rejects a missing sku and a negative price, and reassigns the parameter name to its stripped form; the stripped value is what ends up in the field.
  3. Printing uses the generated toString: the record's name and each component, Product[sku=D-1, name=Standing desk, price=299.00]. The surrounding spaces are gone, thanks to the compact constructor.
  4. same has equal components, so equals is true, the hash codes match, and a HashSet of both has size 1. No equality code was written.
  5. Records are immutable, so "changing" one means making a new one. withPrice is the usual pattern (a "wither"): sale costs 249.00 and desk still costs 299.00.
  6. new Product("D-2", "Chair", new BigDecimal("-1")) fails in the compact constructor, so an invalid Product can never exist: rejected: price can't be negative: -1. That's the record's strongest feature: validate once, at construction, and every instance is valid.
AdvancedRecords are shallowly immutable

A record's fields are final, but a final field can point to a mutable object. Hand a record a List, change the list, and the record changes. The fix is the same defensive copy as for any immutable class, in the compact constructor.

Orders.java
record LeakyOrder(String id, List<String> items) {}

record Order(String id, List<String> items) {
    Order {
        items = List.copyOf(items);
    }
}

void main() {
    var items = new ArrayList<>(List.of("keyboard"));
    var leaky = new LeakyOrder("A1", items);
    var order = new Order("A1", items);

    items.add("mouse");
    IO.println(leaky);
    IO.println(order);
}
Terminal
$ java Orders.java
LeakyOrder[id=A1, items=[keyboard, mouse]]
Order[id=A1, items=[keyboard]]
What’s happening
  1. Both records receive the same ArrayList, [keyboard].
  2. LeakyOrder stores the caller's list. When the caller adds mouse, the record's items() changes too: LeakyOrder[id=A1, items=[keyboard, mouse]]. Its equals and hashCode change with it, the mutable-key problem from the last topic.
  3. Order's compact constructor replaces the parameter with List.copyOf(items), an unmodifiable copy, so it still prints [keyboard].
  4. Interviewers ask "are records immutable?" precisely for this: shallowly. Copy mutable components in the compact constructor.
AdvancedWhat records can't do
Field.java
record Point(int x, int y) {
    int z;
}

void main() {
    IO.println(new Point(1, 2));
}
Move.java
record Point(int x, int y) {
    void moveRight() {
        this.x = x + 1;
    }
}

void main() {
    IO.println(new Point(1, 2));
}
Terminal
$ java Field.java
Field.java:2: error: field declaration must be static
    int z;
        ^
  (consider replacing field with record component)
1 error
error: compilation failed
$ java Move.java
Move.java:3: error: cannot assign a value to final variable x
        this.x = x + 1;
            ^
1 error
error: compilation failed
What’s happening
  1. int z; is an instance field that isn't a component. Records forbid it, because the header must describe the record's entire state; a static field would be allowed.
  2. this.x = x + 1 assigns a component field, which is final. A record that needs to "move" returns a new record instead: Point moveRight() { return new Point(x + 1, y); }.
  3. Both are compile errors (the compiler even suggests the fix for the first: make it a record component), and neither program runs.

#Enums

Added

A Java enum is not a set of named numbers, as in C or TypeScript's numeric enums. Each constant is an object, the only instance of its value, created once when the enum is loaded. The enum is a full class: it can have fields, a constructor, methods, even a different method body per constant. And because each constant exists exactly once, comparing enums with == is correct and safe.

The compiler gives every enum values() (all constants, in declaration order), valueOf(String) (the constant with that exact name), name() and ordinal() (its position, from 0). There are also two collections built for enums, EnumSet and EnumMap, which store their contents as a bit set or an array indexed by ordinal, so they're very compact and fast.

Compared with TypeScript: a string union type Status = "NEW" | "PAID" is the closest everyday equivalent. A Java enum adds behaviour and data to each value, and switch over an enum can be checked for exhaustiveness, like a TypeScript switch with a never check.

The mental model: an enum is a class with a fixed guest list. Nobody else can be created, and each guest can carry their own details.

Statuses.java
enum OrderStatus {
    NEW("New"), PAID("Paid"), SHIPPED("Shipped"), DELIVERED("Delivered"), CANCELLED("Cancelled");

    private final String label;

    OrderStatus(String label) {
        this.label = label;
    }

    String label() {
        return label;
    }

    boolean canMoveTo(OrderStatus next) {
        return switch (this) {
            case NEW -> next == PAID || next == CANCELLED;
            case PAID -> next == SHIPPED || next == CANCELLED;
            case SHIPPED -> next == DELIVERED;
            case DELIVERED, CANCELLED -> false;
        };
    }
}

void main() {
    for (var status : OrderStatus.values()) {
        IO.println(status.ordinal() + " " + status + " (" + status.label() + ")");
    }

    var status = OrderStatus.valueOf("PAID");
    IO.println("PAID -> SHIPPED: " + status.canMoveTo(OrderStatus.SHIPPED)
            + ", PAID -> NEW: " + status.canMoveTo(OrderStatus.NEW));
    IO.println("== works: " + (status == OrderStatus.PAID));

    var counts = new EnumMap<OrderStatus, Integer>(OrderStatus.class);
    for (var s : List.of(OrderStatus.PAID, OrderStatus.NEW, OrderStatus.PAID)) {
        counts.merge(s, 1, Integer::sum);
    }
    IO.println(counts);

    try {
        OrderStatus.valueOf("paid");
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}
Terminal
$ java Statuses.java
0 NEW (New)
1 PAID (Paid)
2 SHIPPED (Shipped)
3 DELIVERED (Delivered)
4 CANCELLED (Cancelled)
PAID -> SHIPPED: true, PAID -> NEW: false
== works: true
{NEW=1, PAID=2}
No enum constant Statuses.OrderStatus.paid
What’s happening
  1. Each constant calls the constructor: NEW("New") creates the one NEW object with label = "New". Enum constructors are private; nothing outside can create another OrderStatus.
  2. values() returns the constants in declaration order. ordinal() is the position (0 to 4), toString() defaults to the name, and label() is the field: 0 NEW (New) … 4 CANCELLED (Cancelled).
  3. canMoveTo switches on this with a switch expression and no default. Because every constant has a case, the compiler accepts it as exhaustive; add a constant later and this switch stops compiling until it's handled. PAID → SHIPPED is true, PAID → NEW is false.
  4. valueOf("PAID") returns the existing PAID object, so status == OrderStatus.PAID is true. With enums, == and equals mean the same thing.
  5. EnumMap keeps keys in declaration order whatever order they were added in: {NEW=1, PAID=2}. merge(s, 1, Integer::sum) adds 1 to the count, or starts it at 1.
  6. valueOf is exact and case-sensitive: valueOf("paid") throws IllegalArgumentException, and the message names the enum (the class is nested in the file's implicit class, Statuses) and the bad name. When parsing user input, normalise it first or catch this.
AdvancedA different method per constant

A constant can have its own body, overriding a method the enum declares. It's a neat, closed version of the strategy pattern:

Operations.java
enum Operation {
    PLUS("+") {
        int apply(int a, int b) { return a + b; }
    },
    TIMES("*") {
        int apply(int a, int b) { return a * b; }
    };

    private final String symbol;

    Operation(String symbol) {
        this.symbol = symbol;
    }

    abstract int apply(int a, int b);

    String show(int a, int b) {
        return a + " " + symbol + " " + b + " = " + apply(a, b);
    }
}

void main() {
    for (var op : Operation.values()) {
        IO.println(op.show(6, 7));
    }
}
Terminal
$ java Operations.java
6 + 7 = 13
6 * 7 = 42
What’s happening
  1. Operation declares abstract int apply(int, int), so every constant must provide a body. PLUS { … } and TIMES { … } are each a small anonymous subclass of Operation.
  2. show is shared: it prints the symbol and calls apply, which dispatches to the constant's own body.
  3. The loop prints 6 + 7 = 13 and 6 * 7 = 42. Adding a constant without an apply would be a compile error.

#Sealed classes and interfaces

Added

A sealed class or interface (Java 17) lists exactly which classes may extend or implement it: sealed interface Payment permits Card, BankTransfer, Voucher. Nobody else can. Each permitted subclass must say how the hierarchy continues: final (no further subclasses; records are final already), sealed (its own closed list), or non-sealed (open again from there). The permitted classes must be in the same package (or the same module, if you use modules), and when they're all in the same file the permits clause can be left out.

Why would you want to close a hierarchy? Because then the compiler knows every possible subtype, and a switch over the sealed type can be checked for completeness, with no default branch hiding forgotten cases. That's Java's version of TypeScript's discriminated unions:

TypeScriptJava 21+
type Payment = { kind: "card"; last4: string } | { kind: "voucher"; code: string }sealed interface Payment permits Card, Voucher {} with record Card(String last4) implements Payment {} …
switch (p.kind) { case "card": … }switch (p) { case Card c -> … }
exhaustiveness via a never check in defaultexhaustiveness checked by the compiler, no default needed
the discriminator is a string fieldthe discriminator is the class itself

The mental model: an interface is an open club; a sealed interface is a club with a printed member list. Because the list is printed, the compiler can tell you when you forgot someone. Chapter 05 covers the switch side in depth: switch patterns, record patterns and exhaustiveness.

Payments.java
sealed interface Payment permits Card, BankTransfer, Voucher {}

record Card(String last4, BigDecimal amount) implements Payment {}
record BankTransfer(String iban, BigDecimal amount) implements Payment {}
record Voucher(String code) implements Payment {}

String describe(Payment payment) {
    return switch (payment) {
        case Card card -> "card ending " + card.last4() + ": " + card.amount();
        case BankTransfer transfer -> "transfer from " + transfer.iban() + ": " + transfer.amount();
        case Voucher voucher -> "voucher " + voucher.code();
    };
}

void main() {
    List<Payment> payments = List.of(
            new Card("4242", new BigDecimal("19.99")),
            new BankTransfer("GB33BUKB20201555555555", new BigDecimal("250.00")),
            new Voucher("WELCOME10"));
    for (var payment : payments) {
        IO.println(describe(payment));
    }
}
Terminal
$ java Payments.java
card ending 4242: 19.99
transfer from GB33BUKB20201555555555: 250.00
voucher WELCOME10
What’s happening
  1. Payment is sealed and permits exactly three implementations. All three are records, which are implicitly final, so they satisfy the "final, sealed or non-sealed" rule without saying so.
  2. describe switches on the payment's type: case Card card -> matches a Card and binds it to card, so the branch can call card.last4() without a cast (pattern matching for switch, Java 21).
  3. There's no default. The compiler knows a Payment can only be a Card, a BankTransfer or a Voucher, and all three are handled, so the switch is exhaustive.
  4. Each payment prints through its own branch: card ending 4242: 19.99, transfer from GB33BUKB20201555555555: 250.00, voucher WELCOME10.
  5. Add a fourth record to permits, say GiftCard, and this switch stops compiling until it handles it. That's the point: in a codebase with forty switches over Payment, the compiler finds every one for you. With an open interface and a default, the new type would fall into default silently.
AdvancedWho may join, and the modifiers they need
Rogue.java
sealed interface Payment permits Card, Cash {}

final class Card implements Payment {}
class Cash implements Payment {}
final class Crypto implements Payment {}

void main() {
    IO.println("never runs");
}
Terminal
$ java Rogue.java
Rogue.java:4: error: sealed, non-sealed or final modifiers expected
class Cash implements Payment {}
^
Rogue.java:5: error: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause)
final class Crypto implements Payment {}
      ^
2 errors
error: compilation failed
What’s happening
  1. Card is permitted and final: fine.
  2. Cash is permitted but says nothing about its own subclasses. A permitted class must be final, sealed or non-sealed, so the compiler asks for one of those modifiers.
  3. Crypto isn't in the permits list at all, so it isn't allowed to implement Payment; the compiler says it's not listed in the permits clause.
  4. Nothing runs. non-sealed is the escape hatch: non-sealed class Cash implements Payment {} would let anyone extend Cash, while Payment itself stays closed.

#Nested, inner, local and anonymous classes

Added

A class can be declared inside another class, or even inside a method. There are four kinds, and the difference that matters is whether the nested class keeps a hidden reference to an object of the outer class:

KindDeclaredHas a hidden outer this?Typical use
static nestedstatic class Builder inside a classnobuilders, helper types, Map.Entry
inner (non-static)class Cursor inside a classyesiterators and views over the outer object
localinside a methodyes, if declared in an instance methoda small type only one method needs
anonymousnew Comparator<>() { … } in an expressionyes, in an instance methodone-off implementations; mostly replaced by lambdas since Java 8

Records, enums and interfaces declared inside a class are always static. An inner class can read the outer object's fields directly, which is convenient, but it means every inner object keeps its outer object alive for as long as it lives. Hand an inner object to a long-lived listener list or cache and the whole outer object can't be garbage-collected: a classic leak (chapter 10).

The mental model: an inner object carries a leash tied to the outer object. A static nested class has no leash. Default to static unless the nested class really needs the outer object.

Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var pizza = new Pizza.Builder("margherita").extra("basil").extra("olives").build();
        System.out.println(pizza);

        var playlist = new Playlist(List.of("Intro", "Verse", "Outro"));
        Playlist.Cursor cursor = playlist.new Cursor();
        System.out.println(cursor.next() + ", " + cursor.next() + ", " + cursor.next() + ", " + cursor.next());

        record Score(String name, int points) {}
        var scores = new ArrayList<>(List.of(new Score("ana", 7), new Score("maya", 12), new Score("rohit", 9)));

        scores.sort(new Comparator<Score>() {
            @Override
            public int compare(Score a, Score b) {
                return Integer.compare(b.points(), a.points());
            }
        });
        System.out.println("anonymous class: " + scores);

        scores.sort(Comparator.comparing(Score::name));
        System.out.println("method reference: " + scores);
    }
}

class Pizza {
    private final String base;
    private final List<String> extras;

    private Pizza(Builder builder) {
        this.base = builder.base;
        this.extras = List.copyOf(builder.extras);
    }

    @Override
    public String toString() {
        return base + " with " + extras;
    }

    static class Builder {
        private final String base;
        private final List<String> extras = new ArrayList<>();

        Builder(String base) {
            this.base = base;
        }

        Builder extra(String topping) {
            extras.add(topping);
            return this;
        }

        Pizza build() {
            return new Pizza(this);
        }
    }
}

class Playlist {
    private final List<String> tracks;

    Playlist(List<String> tracks) {
        this.tracks = tracks;
    }

    class Cursor {
        private int position = 0;

        String next() {
            String track = tracks.get(position);
            position = (position + 1) % tracks.size();
            return track;
        }
    }
}
Terminal
$ java Main.java
margherita with [basil, olives]
Intro, Verse, Outro, Intro
anonymous class: [Score[name=maya, points=12], Score[name=rohit, points=9], Score[name=ana, points=7]]
method reference: [Score[name=ana, points=7], Score[name=maya, points=12], Score[name=rohit, points=9]]
What’s happening
  1. Pizza.Builder is a static nested class: it's created with new Pizza.Builder(...), no Pizza needed. It can call Pizza's private constructor because nested classes share their outer class's private access. Each extra returns this, so calls chain, and build() makes the immutable Pizza: margherita with [basil, olives].
  2. Playlist.Cursor is an inner class: it reads tracks, a field of the outer object, with no qualifier. That only works because each Cursor belongs to a particular Playlist, which is why it's created with the odd-looking playlist.new Cursor().
  3. The cursor wraps around: Intro, Verse, Outro, Intro.
  4. record Score is a local record, declared inside main and invisible outside it. Local records are handy for an intermediate result in one method.
  5. The first sort uses an anonymous class: a Comparator<Score> with one method, written inline, highest points first: maya, rohit, ana. That's Java 6 style.
  6. The second sort does the same job with a method reference (Comparator.comparing(Score::name), by name this time): one line instead of six. Since Java 8, a lambda or method reference replaces an anonymous class whenever the interface has a single abstract method.
AdvancedThe hidden reference, and what this means
Outer.java
public class Outer {
    private String label = "outer object";

    class Inner {
        String describe() {
            return "inner can see the " + label;
        }
    }

    static class Nested {
        String describe() {
            return "nested sees nothing of Outer";
        }
    }

    Runnable anonymous() {
        return new Runnable() {
            @Override
            public void run() {
                System.out.println("anonymous: this has no class name: " + this.getClass().getSimpleName().isEmpty()
                        + ", Outer.this is the " + Outer.this.label);
            }
        };
    }

    Runnable lambda() {
        return () -> System.out.println("lambda: this is the " + this.label);
    }

    public static void main(String[] args) {
        var outer = new Outer();
        System.out.println(outer.new Inner().describe());
        System.out.println(new Nested().describe());
        outer.anonymous().run();
        outer.lambda().run();
    }
}
Terminal
$ javac Outer.java
$ ls
Outer.class
Outer.java
Outer$1.class
Outer$Inner.class
Outer$Nested.class
$ java Outer
inner can see the outer object
nested sees nothing of Outer
anonymous: this has no class name: true, Outer.this is the outer object
lambda: this is the outer object
$ javap -p 'Outer$Inner' 'Outer$Nested'
Compiled from "Outer.java"
class Outer$Inner {
  final Outer this$0;
  Outer$Inner(Outer);
  java.lang.String describe();
}
Compiled from "Outer.java"
class Outer$Nested {
  Outer$Nested();
  java.lang.String describe();
}
What’s happening
  1. javac writes a separate class file for each nested class, named with a $, as ls shows: Outer$Inner.class, Outer$Nested.class, and Outer$1.class for the anonymous class (the lambda gets no class file; it's created at run time). The JVM has no nested classes; the compiler flattens them.
  2. javap -p shows what the compiler added: Outer$Inner has a field final Outer this$0 and a constructor that takes an Outer. That field is the leash. Outer$Nested has neither.
  3. Inside the anonymous class, this is the anonymous object itself (its simple name is empty, so the check prints true), and the outer object is reached as Outer.this.
  4. Inside the lambda, this is the enclosing Outer: a lambda isn't an object with its own this, which is one reason lambdas are simpler. (JavaScript arrow functions behave the same way, taking this from where they're written.)
  5. A current javac leaves out this$0 when an inner class never uses the outer object (tried for this page: javac 25 omits it, and the same class compiled with --release 17 keeps it). Don't rely on that: if the class doesn't need the outer object, declare it static and the question never arises.

#Your turn: modelling with classes and records

Added
Your turn: a Money value object

Write a record Money(String currency, BigDecimal amount) that rejects currencies that aren't three capital letters, always stores the amount with 2 decimal places (so 10 and 10.00 are equal), and has plus(Money other) that refuses to add different currencies. Show that EUR 10 equals EUR 10.00, that 10 + 5.5 is 15.50, and that adding GBP to EUR fails.

Show answer
MoneyDemo.java
record Money(String currency, BigDecimal amount) {
    Money {
        if (currency == null || !currency.matches("[A-Z]{3}")) {
            throw new IllegalArgumentException("currency must be 3 capital letters: " + currency);
        }
        amount = amount.setScale(2, RoundingMode.HALF_EVEN);
    }

    static Money of(String currency, String amount) {
        return new Money(currency, new BigDecimal(amount));
    }

    Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("can't add " + other.currency + " to " + currency);
        }
        return new Money(currency, amount.add(other.amount));
    }
}

void main() {
    var ten = Money.of("EUR", "10");
    IO.println(ten + " equals EUR 10.00: " + ten.equals(Money.of("EUR", "10.00")));
    IO.println(ten.plus(Money.of("EUR", "5.5")));

    try {
        ten.plus(Money.of("GBP", "1"));
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
    try {
        Money.of("eur", "1");
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}
Terminal
$ java MoneyDemo.java
Money[currency=EUR, amount=10.00] equals EUR 10.00: true
Money[currency=EUR, amount=15.50]
can't add GBP to EUR
currency must be 3 capital letters: eur
What’s happening
  1. The compact constructor runs for every Money, however it's created. It checks the currency with a regular expression and normalises the amount with setScale(2, …), so 10 is stored as 10.00.
  2. That normalisation is what makes equals work: BigDecimal.equals compares scale too (chapter 02), and both amounts now have scale 2, so Money[currency=EUR, amount=10.00] equals EUR 10.00: true.
  3. plus checks the currencies, then returns a new Money; 10.00 + 5.50 gives Money[currency=EUR, amount=15.50]. Records are immutable, so there's no way to change ten itself.
  4. Adding GBP to EUR throws with can't add GBP to EUR, and a lowercase currency never gets past the constructor.
  5. Money.of is a static factory: a readable name, and it keeps the new BigDecimal(String) rule from chapter 02 in one place.
Your turn: shapes with a sealed interface

Model Circle(radius), Rectangle(width, height) and Square(side) as records under a sealed interface Shape, write area(Shape) with a switch that has no default, and print the shapes sorted by area, largest first, with areas to two decimal places.

Show answer
Shapes.java
sealed interface Shape permits Circle, Rectangle, Square {}

record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Square(double side) implements Shape {}

double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Rectangle r -> r.width() * r.height();
        case Square s -> s.side() * s.side();
    };
}

void main() {
    var shapes = new ArrayList<Shape>(List.of(new Square(3), new Circle(2), new Rectangle(2, 5)));
    shapes.sort(Comparator.comparingDouble(this::area).reversed());
    for (var shape : shapes) {
        IO.println("%-33s %.2f".formatted(shape, area(shape)));
    }
}
Terminal
$ java Shapes.java
Circle[radius=2.0]                12.57
Rectangle[width=2.0, height=5.0]  10.00
Square[side=3.0]                  9.00
What’s happening
  1. Shape is sealed with three record implementations, so the switch in area covers every case and needs no default.
  2. The areas: the circle is π × 2 × 2 ≈ 12.57, the rectangle 2 × 5 = 10.00, the square 3 × 3 = 9.00.
  3. Comparator.comparingDouble(this::area) sorts by area, and .reversed() makes it largest first. this::area works because, in a compact source file, area is an instance method of the implicit class and main is an instance method too.
  4. "%-33s %.2f" left-aligns the record's toString in 33 columns and prints the area with two decimals: the circle first, then the rectangle, then the square.
  5. Add record Triangle(double base, double height) implements Shape {} to the permits list and area stops compiling until you add its case.
Your turn: fix the duplicate emails

This class is used in a HashSet, and "Ana@Example.com" and "ana@example.com" both end up in it, as do two identical addresses. Rewrite it so that the set holds one entry per address, ignoring case, and invalid addresses (no @) are rejected.

Broken.java
import java.util.HashSet;
import java.util.List;

public class Broken {
    public static void main(String[] args) {
        var emails = new HashSet<Email>();
        for (String raw : List.of("Ana@Example.com", "ana@example.com", "ana@example.com")) {
            emails.add(new Email(raw));
        }
        System.out.println(emails.size() + " entries");
    }
}

class Email {
    private final String value;

    Email(String value) {
        this.value = value;
    }

    public boolean equals(Email other) {
        return value.equals(other.value);
    }
}
Terminal
$ java Broken.java
3 entries
Show answer
Fixed.java
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

public class Fixed {
    public static void main(String[] args) {
        var emails = new HashSet<Email>();
        for (String raw : List.of("Ana@Example.com", "ana@example.com", "ana@example.com")) {
            emails.add(new Email(raw));
        }
        System.out.println(emails.size() + " entry: " + emails);

        try {
            new Email("not-an-address");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

record Email(String value) {
    Email {
        value = value.strip().toLowerCase(Locale.ROOT);
        if (!value.contains("@")) {
            throw new IllegalArgumentException("not an email address: " + value);
        }
    }
}
Terminal
$ java Fixed.java
1 entry: [Email[value=ana@example.com]]
not an email address: not-an-address
What’s happening
  1. The broken class had two bugs: equals(Email) overloads instead of overriding equals(Object), so HashSet never calls it, and there's no hashCode, so every object gets its own identity hash. All three addresses were kept.
  2. A record fixes both at once: its generated equals(Object) and hashCode() use the value component.
  3. The compact constructor normalises before the field is set: strip spaces and lowercase. Locale.ROOT makes lowercasing independent of the computer's language settings (in a Turkish locale, "I".toLowerCase() isn't "i").
  4. After normalisation all three inputs are ana@example.com, equal records with equal hash codes, so the set holds one: 1 entry: [Email[value=ana@example.com]].
  5. An address without @ is rejected in the constructor, so no invalid Email can exist anywhere in the program.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.