Initialisation order — a common quiz question#
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();1. static block (class loaded)
2. instance initializer
3. constructor
2. instance initializer
3. constructorWith 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
finalclass can't be extended.Stringis final — so nobody can create a subclass that breaks its immutability (Classes, Objects and Memory Ch 6).A
finalmethod can't be overridden — use it when a subclass changing the behaviour would break an invariant.(A
finalvariable can't be reassigned — Classes, Objects and Memory Ch 5.)
Check yourself
2 questionsHow many times does a static block run?
Show answerHide answer
Once, when the class is first loaded/used.
Why is String a final class?
Show answerHide answer
So no subclass can alter its behaviour and break immutability or the security guarantees built on it.