Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Initialisation Order, final Classes and Methods

    static { System.out.println("1. static block (class loaded)"); } // runs ONCE, when the class is first used

    Chapter 9 of 122 min read

    Initialisation order — a common quiz question#

    Java
    class InitOrder {
        static {
            System.out.println("1. static block (class loaded)");
        } // runs ONCE, when the class is first used
    
        {
            System.out.println("2. instance initializer");
        } // runs for EVERY new object, before the constructor body
    
        InitOrder() {
            System.out.println("3. constructor");
        }
    }
    
    new InitOrder();
    
    new InitOrder();
    Output
    1. static block (class loaded)
    2. instance initializer
    3. constructor
    2. instance initializer
    3. constructor

    With inheritance, the full order is: parent static → child static (once, at class loading — Inside the JVM), then for each object: parent field initialisers and constructor → child field initialisers and constructor.

    final on classes and methods#

    • A final class can't be extended. String is final — so nobody can create a subclass that breaks its immutability (Classes, Objects and Memory Ch 6).

    • A final method can't be overridden — use it when a subclass changing the behaviour would break an invariant.

    • (A final variable can't be reassigned — Classes, Objects and Memory Ch 5.)

    Check yourself

    2 questions
    1

    How many times does a static block run?

    Show answer

    Once, when the class is first loaded/used.

    2

    Why is String a final class?

    Show answer

    So no subclass can alter its behaviour and break immutability or the security guarantees built on it.