Prasanna Peethambaram’s Post

🧱Blocks — The Execution Order One common Java interview question: When Parent and Child classes both have static blocks, instance blocks, and constructors — what runs first? Few understand why. 🧠 First Principle: How Java Builds an Object When creating a Child object, Java does not build the child first. It builds the Parent part first, then completes the Child. Object creation always happens top → down in the inheritance chain. ⚙️ Step 1: Class Loading Phase (Runs Only Once) Static blocks belong to the class, not the object. They execute when the class is loaded into memory. Execution Order 1️⃣ Parent static block 2️⃣ Child static block No matter how many objects you create later → static blocks won’t run again. 🏗 Step 2: Object Creation Phase (Runs Every Object Creation) For each class in inheritance: ➡️ Instance Block ➡️ Constructor So full execution becomes: Parent static Child static Parent instance block Parent constructor Child instance block Child constructor 🎯 Why This Happens Because a Child object literally contains a Parent inside it. Java must construct the Parent portion first before finishing the Child portion. 📌 Where Blocks Are Used Static blocks • Loading drivers • Initializing configuration • Creating caches • One-time setup logic Instance blocks • Shared constructor logic (rare; constructors preferred) GitHub Link: https://lnkd.in/gj6uhVv3 🔖Frontlines EduTech (FLM) #JAVA #corejava #blocks #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #instance #static #constructor

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories