Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Nested classes and interfaces in Java

Distinguish static nested classes from inner classes, expose builder steps through public interfaces, and give a nested LRU cache its own type parameters.

Version: Java SE 21

Syntax

class Outer {
    public interface Step { Result build(); }
    private static final class Builder implements Step {
        public Result build() { return new Result(); }
    }
    public static final class Result {}
    static class LRUCache<K,V> {}
    class Inner {}
}
// Where accessible: new Outer.Result() vs. outer.new Inner()

A static nested class has no implicit enclosing instance. From outside, refer to it as Outer.Nested and, if the constructor is accessible, create it with new Outer.Nested(). To access instance members on a separate object of the enclosing class, use an explicit reference to that object. If the nested class extends the enclosing class, its instance methods can access inherited instance members through their own implicit this. In contrast, a non-static member class (an inner class) has an enclosing instance and can be created with outer.new Inner().

In static final class, static means there is no enclosing instance, while final prevents subclassing. Neither modifier makes objects immutable. In private static final class Builder, private also hides the implementation type from client code outside the enclosing class.

Java's nested interfaces are implicitly static; a member interface declared in a class is not automatically public. In the example, the public interfaces Main.TitleStep and Main.BuildStep define which operations are available. The return type of builder() does not expose build(); calling title(...) returns a type that does.

static class LRUCache<K,V> declares its own type parameters: K for keys and V for values. It cannot use the enclosing class's type parameters. The example uses an access-ordered LinkedHashMap and calls pollFirstEntry() to evict the least recently accessed entry when the size exceeds the limit. That method comes from the Java SE 21 API; the example cache is not thread-safe.

Examples

import java.util.LinkedHashMap;

public class Main {
    public interface TitleStep {
        BuildStep title(String title);
    }

    public interface BuildStep {
        Report build();
    }

    public static TitleStep builder() {
        return new Builder();
    }

    private static final class Builder implements TitleStep, BuildStep {
        private String title;

        @Override
        public BuildStep title(String title) {
            this.title = title;
            return this;
        }

        @Override
        public Report build() {
            return new Report(title);
        }
    }

    public static final class Report {
        private final String title;

        private Report(String title) {
            this.title = title;
        }

        public String title() {
            return title;
        }
    }

    static class LRUCache<K,V> {
        private final int limit;
        private final LinkedHashMap<K,V> entries = new LinkedHashMap<>(16, 0.75f, true);

        LRUCache(int limit) {
            if (limit < 1) {
                throw new IllegalArgumentException("limit must be positive");
            }
            this.limit = limit;
        }

        V get(K key) {
            return entries.get(key);
        }

        void put(K key, V value) {
            entries.put(key, value);
            if (entries.size() > limit) {
                entries.pollFirstEntry();
            }
        }
    }

    public static void main(String[] args) {
        Report report = Main.builder().title("Report").build();
        System.out.println(report.title());

        Main.LRUCache<String, Integer> cache = new Main.LRUCache<>(2);
        cache.put("a", 1);
        cache.put("b", 2);
        System.out.println(cache.get("a"));
        cache.put("c", 3);
        System.out.println(cache.get("b"));
    }
}

Result

Report
1
null

The program never creates a `Main` object. Reading `a` returns `1` and updates the access order, so adding `c` evicts `b`. The later read of `b` returns `null`.

Related lessons

  • Java · Lesson 37 · Intermediate · Version: 2
  • Java · Lesson 38 · Intermediate · Version: 2
  • Java · Lesson 40 · Intermediate · Version: 2

Sources