0/0
OOP Fundamentals

Class Internals & Object Copying

Explore initialization blocks, nested classes, and object copying mechanisms — the hidden plumbing inside Java classes.

Object Initialization Order
Loading diagram...
Types of Nested Classes in Java
Loading diagram...
Explore Topics
1
Alternatives to constructors for setting up state
Initialization Blocks
🚀 Object Birth Simulator— step through initialization order
1
Class Loading
class-load
2
Static Block A
class-load
3
Static Block B
class-load
4
new ClassName()
per-object
5
Instance Block A
per-object
6
Field Initializer
per-object
7
Instance Block B
per-object
8
Constructor Body
constructor
⚡

Initialization Blocks

Alternatives to constructors for setting up state

Initialization blocks are code blocks inside a class that run automatically. Static blocks run once when the class is loaded by the JVM. Instance initialization blocks (IIB) run every time a new object is created — before the constructor body executes. They provide an alternative way to set up state without relying solely on constructors.

Key Ideas
1Static init blocks: execute once during class loading (before any objects are created)
2Instance init blocks (IIB): execute every time a new object is created
3Instance blocks run before the constructor body
4Syntax: static { ... } for static blocks, { ... } for instance blocks
5Both can access fields and call methods appropriate to their scope
Strengths
  • ✦Provide initialization logic separate from constructors
  • ✦Static blocks are ideal for one-time class-level setup
  • ✦Instance blocks share logic across multiple constructors
  • ✦Can contain complex initialization logic with loops, conditionals, and exception handling
Weaknesses
  • △Can make initialization flow harder to follow if overused
  • △Static blocks run in a fixed order — difficult to test
  • △Exceptions in static blocks cause ExceptionInInitializerError
Used in:JDBC driver registration, singleton caches, logging setup, resource pool initialization

Initialization Blocks Quiz

Initialization Blocks Quiz
QUIZ 1/7
How many times does a static initialization block execute?

Practice Exercises

Order these initialization steps from first to last when creating a new object:
EXERCISE 1/3
Static init block
Instance init block
Constructor body
Field initializer
Class loading by JVM
1st — Class Loading Phase
2nd — Runs Once
3rd — Per Object (source order)
4th — Last Step
Classify each feature: Static Nested Class or Inner Class?
EXERCISE 2/3
No outer instance needed
Can access all outer members
Can only access static outer members
Holds hidden outer reference
Created with outer.new
Created with new Outer.Nested()
Static Nested Class
Inner Class
Match each copying approach to its characteristic:
EXERCISE 3/3
Shares mutable references
Fully independent objects
Faster (less allocation)
Safe from shared-state bugs
Can cause unexpected side effects
Creates new collections for fields
Shallow Copy
Deep Copy