ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Classes
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 4.1

Classes

Class declaration, fields, methods, constructors, initialisation blocks and nested classes

14 min readStage 1 · Foundations14 interview questions
Prerequisites
Chapter 2 · Chapter 3
Covers
Class declaration · Fields · Methods · Constructors · Initialization blocks · Nested classes
Related
4.2 Objects · 4.3 Constructors · 5.1 Encapsulation · Chapter 8 (nested classes)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A class is a named blueprint that defines the state (fields) and behaviour (methods) of its objects, how they are created (constructors), and optionally supporting code and types (initialisation blocks and nested classes). The class itself exists once per class loader; objects created from it can exist in any number.

The members a class can declare
Figure 1 — The members a class can declare
One class definition, many independent objects
Figure 2 — One class definition, many independent objects

2Why It Exists

Classes group data with the operations that are valid on it. Instead of passing raw values to free functions that each must remember the rules, a class keeps the rules next to the data. This is the basis of encapsulation (Chapter 5), reuse through composition and inheritance (Chapters 6–7), and the component structure of frameworks such as Spring.

3Core Concepts

Class declaration

A declaration names the class and states its modifiers, superclass and interfaces: public final class Order extends BaseEntity implements Auditable. Top-level classes are public or package-private. Modifiers such as abstract (cannot be instantiated), final (cannot be subclassed) and sealed (only permitted subclasses) express design intent the compiler enforces.

Fields

Fields hold state. Instance fields exist once per object; static fields once per class (2.3). A field is usually private, often final, and initialised either where it is declared or in a constructor. final fields must be assigned exactly once by the end of construction, which is the foundation of immutable classes.

Methods

Methods define behaviour. Instance methods operate on a particular object and can use this; static methods belong to the class and have no this. Methods are covered in detail in 4.4.

Constructors

Constructors have the class's name, no return type, and run when an object is created to put it into a valid initial state. They can be overloaded and chained (4.3).

Initialization blocks

A static initialiser (static { … }) runs once when the class is initialised — useful for complex static setup such as building a lookup table. An instance initialiser ({ … }) runs for every object, before the constructor body, in textual order with field initialisers. Instance initialisers are rarely needed: constructors, or private methods called from them, are clearer.

Order in which initialisation code runs
Figure 3 — Order in which initialisation code runs

Nested classes

A class can declare other types inside it: static nested classes, inner classes, local classes and anonymous classes, as well as nested records, enums and interfaces. Nested types express that a type belongs to, or only makes sense with, its enclosing class — for example Order.Line or a builder Order.Builder. Chapter 8 covers the kinds and their memory implications.

4How It Works Internally

javac compiles each class, and every nested type inside it, to its own class file (Figure 4). Nested types get binary names joined by $, such as Order$Line and Order$Status. Inside Order.class, each constructor becomes a method named <init>, which also carries the field initialisers and instance initialiser blocks, and all static field initialisers and static blocks are merged, in text order, into one method named <clinit>. The javap listing below shows the result for Example 1: the private fields, the constructor Order(long), the two methods, and static {}, which is how javap prints <clinit> (the long first field line is wrapped here).

TERMINAL
$ javac Order.java
$ ls *.class
Order$Line.class  Order$Status.class  Order.class
$ javap -p Order
Compiled from "Order.java"
public final class Order {
  private static final java.util.Map<java.lang.String, java.lang.Integer>
      PRIORITY;
  private final long id;
  private final java.util.List<Order$Line> lines;
  private Order$Status status;
  public Order(long);
  public void addLine(java.lang.String, int);
  public static int priorityOf(java.lang.String);
  static {};
}
One source file, three class files: constructors become <init>, static initialisation becomes <clinit>
Figure 4 — One source file, three class files: constructors become <init>, static initialisation becomes <clinit>

At run time a class is loaded lazily, the first time code needs it, and is identified by its name together with the class loader that defined it. Its metadata (bytecode, field layout, constant pool) lives in metaspace, outside the heap, while its static fields are stored once per loaded class, not once per object. The JVM initialises the class, that is, runs <clinit>, on its first active use: creating an instance, calling a static method, or using a static field that is not a compile-time constant (1.2). Initialisation is guarded by a lock, so exactly one thread runs it even when many threads touch the class at once, and the others wait until it has finished. Example 3 relies on that guarantee.

Each object has a header and its own copy of the instance fields (4.2); methods are never copied into objects. An instance method is shared code that receives the object as a hidden first parameter, this. A static method has no such parameter, which is why it cannot use instance fields without an object to read them from.

5APIs / Features / Syntax

The declaration forms below cover nearly every class in a modern codebase. Each modifier is checked by the compiler, so it turns a design decision into a rule that cannot be broken by accident.

FormExampleUse it for
public final classpublic final class OrderThe default for concrete classes: no subclass can change their behaviour
Package-private classclass PriceRulesHelpers that only their own package should see
abstract classabstract class ShapeA partial implementation that subclasses complete (6.1)
sealed ... permits (Java 17)sealed interface Payment permits Card, UpiA closed set of subtypes; switch can check that every case is handled
record (Java 16)record Money(BigDecimal amount, Currency currency)Immutable data carriers; equals, hashCode and toString are generated
enumenum Status { NEW, PAID }A fixed set of instances
Static nested classstatic final class BuilderA helper that belongs to the outer class but needs no outer instance
Inner classclass Itr implements Iterator<E>A helper that needs the outer object; it holds a hidden reference to it (Chapter 8)

Java 25 also accepts a compact source file: a main method with no class declaration around it, which the compiler wraps in an implicit final class (1.1). It is meant for scripts and first programs; once code is shared or tested, a named class is clearer. At run time the same structure is visible through Class: getDeclaredFields(), getDeclaredConstructors(), isRecord(), isSealed() and getPermittedSubclasses() are what frameworks use to read a class's members.

6Practical Examples

Example 1 — A class with each kind of member

JAVAA class with each kind of member
public final class Order {

    private static final Map<String, Integer> PRIORITY;   // static state
    static {                                               // static initialiser
        PRIORITY = Map.of("EXPRESS", 1, "STANDARD", 2);
    }

    private final long id;                                 // instance fields
    private final List<Line> lines = new ArrayList<>();    // field initialiser
    private Status status = Status.NEW;

    public Order(long id) {                                // constructor
        this.id = id;
    }

    public void addLine(String sku, int qty) {             // instance method
        if (status != Status.NEW) throw new IllegalStateException("locked");
        lines.add(new Line(sku, qty));
    }

    public static int priorityOf(String type) {            // static method
        return PRIORITY.getOrDefault(type, 3);
    }

    public record Line(String sku, int qty) {}             // nested record
    public enum Status { NEW, PAID, SHIPPED }              // nested enum
}

What to notice. The static members, PRIORITY, its static block and priorityOf, exist once for the class; id, lines and status exist once per order. Line and Status are public because callers need them, and final on the class means that no subclass can bypass the check in addLine. Section 4 shows what javac makes of this one file.

Example 2 — Mini program: tracing when each part of a class runs

Problem. Section 3 lists the parts of a class, and Figure 3 shows the order in which their initialisation code runs. This program prints a line from each part, so you can see the order instead of memorising it: a static field, a static initialiser, a field initialiser that uses the static state, an instance initialiser and a constructor, for two objects.

JAVAInitTrace.java
public class InitTrace {
    static class Ticket {
        private static int issued;                       // static field
        private static final String PREFIX;
 
        static {                                         // static initialiser
            PREFIX = "T-";
            log("static block: PREFIX set, issued = " + issued);
        }
 
        private final String id = PREFIX + (++issued);   // field initialiser
        private final String owner;
 
        {                                                // instance initialiser
            log("instance block: id = " + id);
        }
 
        Ticket(String owner) {                           // constructor
            this.owner = owner;
            log("constructor: owner = " + owner);
        }
 
        @Override public String toString() { return id + "/" + owner; }
    }
 
    static void log(String s) { System.out.println("  " + s); }
 
    public static void main(String[] args) {
        System.out.println("main starts");
        System.out.println("first new Ticket:");
        Ticket a = new Ticket("asha");
        System.out.println("second new Ticket:");
        Ticket b = new Ticket("ravi");
        System.out.println(a + ", " + b + ", issued = " + Ticket.issued);
    }
}
OUTPUT
main starts
first new Ticket:
  static block: PREFIX set, issued = 0
  instance block: id = T-1
  constructor: owner = asha
second new Ticket:
  instance block: id = T-2
  constructor: owner = ravi
T-1/asha, T-2/ravi, issued = 2

Why it behaves this way. The static block runs once, before the first object, because new Ticket(...) is the first active use of the class; issued is still 0 there, because the static field has only its default value at that point. For each object, the field initialiser id = PREFIX + (++issued) and then the instance block run, in text order, before the constructor body: javac has copied both into the constructor (section 4). The second object repeats only the per-object steps. main can read the private field Ticket.issued because a nested class and its enclosing class share private access.

Example 3 — Deferring expensive static setup: the holder idiom

Problem. Section 7 warns against heavy work in static initialisers: it runs at an unpredictable moment, slows the first request, and a failure leaves the class unusable. When some static data is expensive and only some callers need it, the holder idiom moves it into a nested class that the JVM initialises only on first use.

JAVALazyHolder.java
public class LazyHolder {
    static final class Pricing {
        static { System.out.println("  Pricing initialised"); }
 
        static int vatPercent() { return 18; }        // needs no rate table
 
        static double fxRate(String currency) {       // first call loads it
            return Rates.TABLE.getOrDefault(currency, 1.0);
        }
 
        private static final class Rates {            // the holder class
            static final Map<String, Double> TABLE = load();
 
            private static Map<String, Double> load() {
                System.out.println("  Rates: loading table (slow I/O)");
                return Map.of("USD", 88.5, "EUR", 102.25);   // sample values
            }
        }
    }
 
    public static void main(String[] args) {
        System.out.println("vat = " + Pricing.vatPercent() + "%");
        System.out.println("USD = " + Pricing.fxRate("USD"));
        System.out.println("EUR = " + Pricing.fxRate("EUR"));
    }
}
OUTPUT
  Pricing initialised
vat = 18%
  Rates: loading table (slow I/O)
USD = 88.5
EUR = 102.25
The holder idiom: the nested class is initialised on first use, once, under the JVM's lock
Figure 5 — The holder idiom: the nested class is initialised on first use, once, under the JVM's lock

Why it behaves this way. Calling vatPercent() initialises Pricing but not Rates: a nested class is a separate class (section 4) and is initialised only when its own static field is first read. The first fxRate call triggers Rates.<clinit>, which runs load(). The class-initialisation lock guarantees that this happens once even if many threads call fxRate together, and afterwards reading TABLE is an ordinary field read with no synchronisation. The idiom does not remove the other risk in Figure 5: if load() throws, Rates is marked as failed and every later call gets NoClassDefFoundError. For data that comes from a network or a database, prefer an explicit component that loads at startup, reports a failure clearly and can retry.

Example 4 — From public fields to a class that guards its state

Problem. Section 9 recommends a small public surface, private fields and illegal states that cannot be represented. This program puts the two styles side by side: a class with public fields, and the same data behind a validating constructor, an enum for the status and methods that enforce the rules.

JAVAShipmentDemo.java
public class ShipmentDemo {
    static class LooseShipment {           // before: public mutable fields
        public String trackingId;
        public String status;              // "NEW", "SHIPPED" ... or a typo
        public List<String> parcels = new ArrayList<>();
    }
 
    static final class Shipment {          // after: rules inside the class
        enum Status { NEW, SHIPPED }
        private final String trackingId;
        private final List<String> parcels = new ArrayList<>();
        private Status status = Status.NEW;
 
        Shipment(String trackingId) {
            if (trackingId == null || !trackingId.matches("[A-Z]{2}\\d{6}"))
                throw new IllegalArgumentException("bad id: " + trackingId);
            this.trackingId = trackingId;
        }
        void addParcel(String parcel) {
            if (status != Status.NEW)
                throw new IllegalStateException("already shipped");
            parcels.add(Objects.requireNonNull(parcel));
        }
        void ship() {
            if (parcels.isEmpty())
                throw new IllegalStateException("no parcels");
            status = Status.SHIPPED;
        }
        @Override public String toString() {
            return trackingId + " " + status + " " + parcels;
        }
    }
 
    static void attempt(Runnable action) {
        try { action.run(); }
        catch (RuntimeException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
 
    public static void main(String[] args) {
        LooseShipment loose = new LooseShipment();
        loose.status = "SHIPED";           // typo, no id, no parcels: accepted
        System.out.println("loose: " + loose.trackingId + " " + loose.status
                + " " + loose.parcels);
 
        Shipment s = new Shipment("IN123456");
        attempt(s::ship);
        s.addParcel("box-1");
        s.ship();
        System.out.println("shipment: " + s);
        attempt(() -> s.addParcel("box-2"));
        attempt(() -> new Shipment("123"));
    }
}
OUTPUT
loose: null SHIPED []
rejected: no parcels
shipment: IN123456 SHIPPED [box-1]
rejected: already shipped
rejected: bad id: 123

Why it behaves this way. LooseShipment accepts anything: a missing tracking ID, a misspelt status and a shipment with no parcels, and nothing reports it until some later code misbehaves. In Shipment, the constructor rejects a malformed ID, the Status enum turns a misspelling into a compile error, and ship() and addParcel() allow only the legal transitions. Because the fields are private and parcels is never handed out, no caller can get round the rules. They now live in one class, which is also where the tests for them belong.

7Common Problems & Mistakes

MistakeWhy it hurtsWhat to do
A "god class" that mixes unrelated responsibilitiesEvery change touches it, so merge conflicts and regressions grow, and it cannot be tested in isolationSplit it by responsibility: one reason to change per class (Book 5, SRP)
Public mutable fieldsAny code can put the object into an invalid state, and the class can never change how it stores its dataKeep fields private and expose behaviour, not data (Example 4, Chapter 5)
Heavy work in static initialisers (network, file I/O)Startup slows; a failure becomes ExceptionInInitializerError and then NoClassDefFoundError on every later use, with no retry (1.2)Load lazily with a holder class (Example 3) or in a startup component that can retry
Initialisation order spread across a long classField initialisers and blocks run in text order, so moving a line changes behaviour, for example a field read before it is setKeep initialisation in one place: the constructor, or one primary constructor the others call
Mutable static fields used as shared stateThere is one copy for all objects and threads: requests see each other's data and tests depend on their orderPass state explicitly or keep it in an injected component; static fields final and immutable
An inner class where a static nested class would doEach instance holds a hidden reference to its outer object, keeping it alive and leaking memoryDeclare nested classes static unless they need the outer instance (Chapter 8)
A utility class that can be instantiated or subclassedCallers create meaningless instances, and a subclass can add state that the static methods ignoreMake it final with a private constructor, or turn it into an injected component

8Performance & Production Considerations

  • Class loading costs startup time and metaspace. Every loaded class takes metaspace outside the heap, and frameworks generate many classes for proxies and serialisation. Count them with -Xlog:class+load and watch metaspace in production; class data sharing and the AOT cache shorten startup by reusing classes that were already loaded and linked (1.2).
  • A static initialiser runs on the request that first touches the class. An expensive one shows up as a slow first request after every deployment. Warm it up at startup or move the work into an explicit initialisation step.
  • Static state is shared by every thread. A static HashMap or SimpleDateFormat used by concurrent requests corrupts data under load. Static fields should be constants, final and immutable, or thread-safe objects.
  • Class-loader leaks. In servers that redeploy applications without restarting the JVM, one static reference from a shared library to an application class keeps the old class loader, with all its classes, in metaspace; repeated redeploys end in OutOfMemoryError: Metaspace.
  • Many small classes cost nothing at run time. The JIT inlines small methods across class boundaries, so splitting a large class by responsibility does not make it slower.

9Architecture & Design Considerations

A class is the smallest unit of design. Good classes are cohesive (one clear purpose), have a small public surface, keep fields private, and make illegal states unrepresentable — for example with final fields, enums for status and validation in constructors. Mark classes final unless they are designed for inheritance; this keeps options open and avoids the fragile-base-class problem (6.4).

10Interview Questions & Answers

Q1L1 · BasicConcept

What can a class contain?

Fields, methods, constructors, static and instance initialisation blocks, and nested types (classes, interfaces, enums, records).

Q2L2 · IntermediateInternals

In what order is a class and its object initialised?

Static field initialisers and static blocks run once, in text order, when the class is initialised. For each new object: memory is zeroed, the superclass constructor runs, then instance field initialisers and instance blocks in text order, then the rest of the constructor body. Example 2 prints each of these steps.

Q3L2 · IntermediateConcept

What is the difference between a static and an instance initialiser?

A static initialiser runs once per class, when the class is initialised. An instance initialiser runs for every object, before the constructor body and after the superclass constructor.

Q4L3 · Senior EngineerTricky

Why should heavy work in static initialisers be avoided?

It runs at an unpredictable moment (first active use), cannot be retried if it fails, and a failure makes the class permanently unusable: the first access throws ExceptionInInitializerError and later accesses NoClassDefFoundError. It also slows startup and makes testing harder.

Q5L3 · Senior EngineerTrade-off

Why do many teams declare classes final by default?

A class not designed for inheritance can be broken by subclasses that override methods relied on internally (the fragile base class problem). Making it final keeps the implementation free to change; the restriction can be relaxed later, whereas removing extensibility is a breaking change.

Q6L4 · Technical ArchitectDesign

How do you judge whether a class is well designed?

It has one clear responsibility and a name that states it, a small public API, private state, invariants established by constructors and maintained by methods, few dependencies (ideally injected), and no need for callers to know its internals. Tests are easy to write without elaborate setup.

Q7L1 · BasicConcept

What does final mean on a class, a method and a field?

A final class cannot be subclassed, a final method cannot be overridden, and a final field must be assigned exactly once: by the end of construction for an instance field, or of class initialisation for a static one. On a field, final fixes the reference, not the object it refers to: elements can still be added to a final List unless the list itself is unmodifiable.

Q8L2 · IntermediateCode

What does this program print?

JAVACounterQuiz.java
public class CounterQuiz {
    static class Counter {
        static int created;
        final int id = ++created;
        { System.out.print("i" + id + " "); }
        Counter() { System.out.print("c" + id + " "); }
    }
 
    public static void main(String[] args) {
        new Counter();
        new Counter();
        System.out.println(Counter.created);
    }
}

It prints i1 c1 i2 c2 2. created is static, so both objects share one counter. For each new Counter(), the field initialiser id = ++created runs first, then the instance block prints i and the id, and then the constructor body prints c. The initialiser and the block run in text order before the constructor body because javac copies them into the constructor, right after the implicit super() call.

Q9L3 · Senior EngineerInternals

What are <init> and <clinit>?

They are the names the class file gives to initialisation code. Each constructor becomes an <init> method, which also contains the field initialisers and instance blocks unless the constructor starts with this(...). All static field initialisers and static blocks are merged, in text order, into a single <clinit> method that the JVM runs once, under a lock, when the class is first actively used. Neither can be called from Java code; javap prints <clinit> as static {} (section 4).

Q10L3 · Senior EngineerTricky

With Example 1's Order, what does Order order = null; System.out.println(order.priorityOf("EXPRESS")); print?

It prints 1 and throws nothing. priorityOf is static, so javac compiles the call as invokestatic from the declared type of order alone; the reference is never read, so its being null does not matter. With -Xlint javac warns that a static method should be called through the class name. The same rule is why static methods are not overridden: a subclass's static method with the same signature hides the parent's, and the declared type decides which one runs.

Q11L3 · Senior EngineerInternals

A static field holds a large cache. Where does it live, and when can it be garbage-collected?

The static field itself is stored with the class, and the objects it refers to are ordinary heap objects that stay reachable as long as the class is loaded. A class is unloaded only when its class loader becomes unreachable, which for the application classes of a normal service means never. A static cache therefore lives until the JVM exits unless it is bounded or cleared, which is why static collections are a common source of memory leaks (1.3).

Q12L3 · Senior EngineerScenario

After a release, the first order fails with ExceptionInInitializerError and every later one with NoClassDefFoundError: Could not initialize class PricingRules. What happened, and how do you fix it?

PricingRules has a static initialiser that threw, probably while loading configuration or reaching a system that was unavailable when the class was first used. The JVM marks a class whose initialisation failed as unusable: the first caller gets ExceptionInInitializerError with the real cause attached, and every later use fails at once with NoClassDefFoundError, without retrying (Figure 5). Find the cause in the first error's stack trace, which is easily missed because only the later errors flood the logs. Then move the work into an explicit startup component that fails fast with a clear message, or can retry, instead of a class that stays broken until the JVM restarts.

Q13L4 · Technical ArchitectTrade-off

One team writes TaxCalculator as a class of static methods; another wants it as an injected component. Which would you choose?

Static methods suit pure functions with no configuration and no dependencies, such as a checksum or Math.max. A tax calculator usually needs rates, effective dates and per-country rules that change, and its callers' tests need to replace it. As an injected object it receives its configuration through its constructor, can have several implementations and can be replaced in tests, at the cost of a little wiring. Choose the component whenever the logic depends on configuration or external data, and keep static methods for small, stable, dependency-free helpers.

Q14L5 · Solution ArchitectDesign

How would you organise the classes of a large codebase so that teams can change their parts independently?

Package by feature, such as order, payment and catalogue, rather than by layer, and make classes package-private by default so that each package exposes only a few public types as its API. Inside a package, prefer small final classes with one responsibility; across packages, depend only on the published types or interfaces. Enforce the boundaries with Java modules or architecture tests in the build, so that a dependency on another team's internal class fails the build instead of surfacing during a refactoring. The class is the unit of design; the package or module is the unit of ownership.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • A class defines fields, methods, constructors, initialisers and nested types.
  • Static members belong to the class; instance members to each object.
  • Initialisation order: static once; then per object — super constructor, field initialisers and blocks, constructor body.
  • Final by default, private fields, valid-state construction.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.