Skip to content
All Posts

Java Notes

A Java language notebook covering static initialization, inner classes, enums, object construction, and related runtime behavior.

Static blocks

A static initialization block runs when its class is initialized, not merely because the source file was compiled. Initialization can be triggered by creating an instance, calling a static method, or reading a non-constant static field. Compile-time constants may be inlined and therefore do not necessarily initialize the declaring class.

Static fields and static blocks run in source order. Parent classes are initialized before child classes, while instance fields and instance initialization blocks run later as part of object construction.

Why inner classes cannot have static declarations

A non-static inner-class instance is tied to an instance of its enclosing class, so Java restricts most static members inside it. A nested class declared with static does not carry that enclosing-instance reference and may declare static members normally. Constant variables are the notable permitted case in a non-static inner class.

Enums

An enum is a class with a fixed set of instances. Enum constants can have fields, constructors, and methods, and each constant may provide its own implementation of an abstract method. Prefer enums over unrelated integer constants when the set of valid values is closed and type safety matters.


Originally published on SegmentFault.