Skills101

AdvancedJava Programming · Lesson 16 of 29 · Updated ·

static, final and Nested Classes in Java — Static Blocks, Inner and Anonymous Classes

You have already used static for main and final for constants. This lesson goes one level deeper: when static code runs, what exactly final protects, and how to put one class inside another. These ideas show up in output-prediction questions in placement tests and in real code you will read at work.

1. static: one copy for the whole class

A static field belongs to the class, not to any object. All objects share one copy. A static method can be called with the class name and has no this.

There is also a static block (static { … }). It runs once, when the JVM first loads the class — before any object is made. An instance block ({ … } without static) runs every time an object is created, just before the constructor body.

class College {
    static String university;
    static int count;
    String name;

    static {
        university = "State Technical University";
        System.out.println("static block: class loaded");
    }

    {
        count++;
        System.out.println("instance block: object #" + count);
    }

    College(String name) {
        this.name = name;
        System.out.println("constructor: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("main starts");
        new College("City College");
        new College("Hill College");
        System.out.println(College.university + ", colleges = " + College.count);
    }
}
main starts
static block: class loaded
instance block: object #1
constructor: City College
instance block: object #2
constructor: Hill College
State Technical University, colleges = 2

Order of initialisation: the static block runs once when the class is first used; then for every new object the instance block runs, then the constructor body

Notice that main starts prints before the static block. The class College is loaded only when the program first uses it (the first new College), not when the program starts.

Order to remember: static block (once) → for each object: instance block → constructor.

2. final: what it really locks

final means "can be assigned only once".

WhereMeaning
final local variablecannot be reassigned
final fieldmust be set once — at declaration or in every constructor
static final fielda class constant, e.g. static final double GST = 0.18;
final methodcannot be overridden
final classcannot be extended (String, Integer)

The most common confusion: a final reference is not the same as an unchangeable object.

import java.util.*;

class Order {
    final int id;                       // "blank final": set once, in the constructor
    static final double GST = 0.18;
    Order(int id) { this.id = id; }
}

public class Main {
    public static void main(String[] args) {
        Order o = new Order(101);
        System.out.println(o.id + " " + Order.GST);

        final List<String> cart = new ArrayList<>();
        cart.add("pen");                // allowed: the list object itself can change
        cart.add("notebook");
        // cart = new ArrayList<>();    // compile error: cart cannot point to another list
        System.out.println(cart);
    }
}
101 0.18
[pen, notebook]

final fixes the arrow from the variable to the object. It does not freeze the object. To make a list that cannot change, use List.of(...) or Collections.unmodifiableList(...).

3. Four kinds of nested classes

A class written inside another class is a nested class. Java has four kinds.

Table of the four nested class kinds: static nested class needs no outer object; inner class is tied to one outer object; local class lives inside a method; anonymous class has no name and is created in one expression

KindWrittenNeeds an outer object?Typical use
static nestedstatic class B inside Anohelper class used only with A (like Map.Entry)
inner (non-static)class B inside Ayesobject that belongs to one outer object
locala class inside a method(method's object, if any)rare; small helper used in one method
anonymousnew Interface() { … }—one-off implementation, e.g. a comparator

Static nested vs inner class

class Bank {
    private String name = "Skills Bank";
    private static int branches = 3;

    static class Branch {               // static nested: no Bank object needed
        String info() { return "branches: " + branches; }
    }

    class Account {                     // inner: tied to one Bank object
        int balance = 500;
        String info() { return name + " account, balance " + balance; }
    }
}

public class Main {
    public static void main(String[] args) {
        Bank.Branch br = new Bank.Branch();
        System.out.println(br.info());

        Bank bank = new Bank();
        Bank.Account acc = bank.new Account();   // note: outerObject.new Inner()
        System.out.println(acc.info());
    }
}
branches: 3
Skills Bank account, balance 500
  • The inner class Account can read the private field name because every Account object carries a hidden reference to its Bank object (written Bank.this inside the class).
  • The static nested class Branch has no such reference, so it can only use static members of Bank directly.

Rule of thumb: if the nested class does not need the outer object's fields, make it static. An inner class keeps its outer object alive in memory for as long as the inner object lives, which can waste memory.

4. Anonymous classes and lambdas

An anonymous class is a class with no name, written and created in one expression. Before Java 8 this was the usual way to pass behaviour, such as a sort order.

import java.util.*;

interface Greeting {
    String greet(String name);
}

public class Main {
    public static void main(String[] args) {
        String prefix = "Hello";                     // effectively final

        Greeting anon = new Greeting() {             // anonymous class
            @Override
            public String greet(String name) {
                return prefix + ", " + name + " (anonymous class)";
            }
        };
        Greeting lambda = name -> prefix + ", " + name + " (lambda)";

        System.out.println(anon.greet("Asha"));
        System.out.println(lambda.greet("Ravi"));

        List<String> names = new ArrayList<>(List.of("Neha", "Om", "Kabir"));
        names.sort(new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return a.length() - b.length();      // shorter names first
            }
        });
        System.out.println(names);
    }
}
Hello, Asha (anonymous class)
Hello, Ravi (lambda)
[Om, Neha, Kabir]
  • Both the anonymous class and the lambda use prefix from the method. Java allows this only if the variable is effectively final — never changed after it is set. Add prefix = "Hi"; anywhere and the code stops compiling.
  • A lambda works only for a functional interface (one abstract method). An anonymous class can also extend a class, implement an interface with several methods, or keep its own fields.
  • Inside an anonymous class, this means the anonymous object. Inside a lambda, this means the enclosing object.

5. Interview quick answers

  • Can a top-level class be static? No. Only nested classes can be static.
  • Can a static method use this? No — there is no object.
  • Can we override a static method? No; a subclass method with the same signature only hides it.
  • Is a final array unchangeable? No. final int[] a = {1, 2}; a[0] = 9; is allowed; a = new int[3]; is not.
  • Why is main static? So the JVM can call it without creating an object first.

Common mistakes

  • Expecting a static block to run when the program starts. It runs when the class is first used.
  • Thinking final List cannot change. Only the variable is fixed; the list can still grow.
  • Forgetting to set a blank final field in one of the constructors (compile error).
  • Writing new Bank.Account() for an inner class. It needs an outer object: bank.new Account().
  • Changing a local variable that a lambda or anonymous class uses — it must be effectively final.

Quick recap

  • static members are shared by all objects; a static block runs once when the class loads.
  • Order: static block (once) → instance block → constructor (per object).
  • final = assign once. A final reference can still point to an object that changes.
  • Nested classes: static nested (no outer object), inner (tied to an outer object), local, anonymous.
  • Prefer static nested classes when you do not need the outer object; prefer lambdas over anonymous classes for functional interfaces.

Practice what you learned

📝 Quiz: static, final and Nested Classes5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →