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
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".
| Where | Meaning |
|---|---|
final local variable | cannot be reassigned |
final field | must be set once — at declaration or in every constructor |
static final field | a class constant, e.g. static final double GST = 0.18; |
final method | cannot be overridden |
final class | cannot 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.
| Kind | Written | Needs an outer object? | Typical use |
|---|---|---|---|
| static nested | static class B inside A | no | helper class used only with A (like Map.Entry) |
| inner (non-static) | class B inside A | yes | object that belongs to one outer object |
| local | a class inside a method | (method's object, if any) | rare; small helper used in one method |
| anonymous | new 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
Accountcan read the private fieldnamebecause everyAccountobject carries a hidden reference to itsBankobject (writtenBank.thisinside the class). - The static nested class
Branchhas no such reference, so it can only usestaticmembers ofBankdirectly.
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
prefixfrom the method. Java allows this only if the variable is effectively final — never changed after it is set. Addprefix = "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,
thismeans the anonymous object. Inside a lambda,thismeans 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
finalarray unchangeable? No.final int[] a = {1, 2}; a[0] = 9;is allowed;a = new int[3];is not. - Why is
mainstatic? 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 Listcannot change. Only the variable is fixed; the list can still grow. - Forgetting to set a blank
finalfield 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
staticmembers 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.