Classes and Objects · Lesson 21 of 42
static, final and Initialisation
Some data belongs to each object – a student's name. Some belongs to the class as a whole – how many students have been created, or the college name every student shares. The static keyword marks class-level members, and final marks things that must not change. Both appear in every Java codebase and every Java interview.
In this lesson
- Static fields vs instance fields
- Static methods and why they can't use
this - Static and instance initialisation blocks, and their order
finalvariables, methods and classes
Static fields: one copy for the class
public class Main {
public static void main(String[] args) {
new Student("Ira");
Student s = new Student("Jay");
System.out.println(Student.count); // access via the class
System.out.println(s.name + " studies at " + Student.college);
Student.college = "LF Academy";
System.out.println(new Student("Kim").name + " → " + Student.college + ", count " + Student.count);
}
}
class Student {
static String college = "LearnFrenzy Institute"; // shared by all
static int count = 0;
String name; // one per object
Student(String name) {
this.name = name;
count++;
}
}
2 Jay studies at LearnFrenzy Institute Kim → LF Academy, count 3
Where the data lives
Student (class)college, count = 3static – one copyobject 1name = "Ira"instanceobject 2name = "Jay"instanceobject 3name = "Kim"instance
Static methods
A static method belongs to the class, so you call it without an object – like Math.max() or Integer.parseInt(). Because there is no current object, a static method cannot use this or instance fields directly.
public class Main {
public static void main(String[] args) {
System.out.println(MathUtils.isPrime(97) + " " + MathUtils.gcd(84, 36));
}
}
class MathUtils {
private MathUtils() {} // utility class: no objects needed
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) if (n % d == 0) return false;
return true;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
true 12
Common mistake: "non-static variable cannot be referenced from a static context"
Inside main (which is static) you can't use an instance field or call an instance method directly – there's no object. Create one first (new Calculator().add(2, 3)), or make the helper method static if it doesn't need object data.
| Can… | Static method | Instance method |
|---|---|---|
| use static fields and methods | Yes | Yes |
use instance fields and this | No | Yes |
| be called without an object | Yes | No |
| be overridden | No (only hidden) | Yes |
Initialisation blocks and order
A static { } block runs once, when the class is first loaded. An instance block { } runs before the constructor body each time an object is created.
public class Main {
public static void main(String[] args) {
System.out.println("main starts");
new Config("A");
new Config("B");
System.out.println("env = " + Config.env);
}
}
class Config {
static String env;
String id;
static {
System.out.println("1. static block (class loaded once)");
env = "production";
}
{
System.out.println("2. instance block");
}
Config(String id) {
System.out.println("3. constructor for " + id);
this.id = id;
}
}
main starts 1. static block (class loaded once) 2. instance block 3. constructor for A 2. instance block 3. constructor for B env = production
Initialisation order
- Class loadingstatic fields + static blocks, once, top to bottom
- new objectinstance fields + instance blocks, top to bottom
- Constructor bodyruns last
final
| Applied to | Means |
|---|---|
| a variable or field | can be assigned only once |
| a method | cannot be overridden by subclasses |
| a class | cannot be extended (e.g. String, Integer) |
import java.util.ArrayList;
import java.util.List;
public class Main {
static final int MAX_USERS = 100; // constant
public static void main(String[] args) {
final List<String> names = new ArrayList<>();
names.add("Asha"); // allowed: the object changes
names.add("Ben");
// names = new ArrayList<>(); // error: the reference is final
System.out.println(names + " (max " + MAX_USERS + ")");
}
}
[Asha, Ben] (max 100)
Interview angle
final makes the reference unchangeable, not the object. A final list can still be modified. For a truly unmodifiable list use List.of(...) or Collections.unmodifiableList(...). Also: final, finally and finalize are three unrelated things.
Practice
Try it yourself
Give each
Orderan automatic id 1, 2, 3… using a static counter.Show solution
public class Main { public static void main(String[] args) { Order a = new Order(), b = new Order(), c = new Order(); System.out.println(a.id + " " + b.id + " " + c.id); } } class Order { private static int nextId = 1; final int id; Order() { id = nextId++; } }1 2 3
Predict the output: a static block prints "S", an instance block prints "I", the constructor prints "C"; main creates two objects.
Show solution
public class Main { public static void main(String[] args) { new Demo(); new Demo(); } } class Demo { static { System.out.print("S "); } { System.out.print("I "); } Demo() { System.out.print("C "); } }S I C I C
Quick check
Why can't a static method use this?
It belongs to the class, not to an object, so there is no current object.
When does a static block run?
Once, when the class is first loaded by the JVM.
Can you add items to a final List?
Yes. final stops reassigning the variable, not changing the object.
Summary
- Static members belong to the class (one copy); instance members belong to each object.
- Static methods can't use
this; utility classes hold static helpers. - Order: static init once → instance init → constructor;
final= assign once / no override / no subclass.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.