KTU OOP Java2024 Scheme • 60M ESE
MODULE 2/Section 2: Inheritance

Constructor Calling Order & Execution in Multilevel Inheritance

HIGH PRIORITY (Prep Guide)Official Syllabus~14 min study
Official KTU 2024 Syllabus Topics Covered Here
Constructor calling orderConstructor execution in inheritance

1. Topic Introduction

When you create an object of a subclass at the bottom of a multilevel chain (like Shipment extends BoxWeight extends Box), multiple constructors run—one for every class in the hierarchy! Knowing the exact order in which those constructors are invoked vs completed is one of the highest-yield tracing topics in Module 2.

2. Start From Zero: Building a 3-Story House: Inspecting Bottom-Up, Pouring Concrete Top-Down

Suppose you order a Shipment (3rd floor) sitting atop BoxWeight (2nd floor) sitting atop Box (ground foundation). Can you furnish the 3rd floor before the foundation exists? No! So when new Shipment() starts, Shipment immediately asks BoxWeight (super()), which asks Box (super()). Then **Box's constructor finishes first (pouring the foundation), followed by BoxWeight, and finally Shipment**!

Key Takeaway: Constructors execute in order of derivation: from Superclass -> Subclass (top-down), whether you write super() explicitly or let javac insert super() automatically!

3. Essential Exam Definitions

Constructor Chaining Across Inheritance
Automatic or explicit invocation of superclass constructors from every subclass constructor via super(...), ensuring base layers are fully initialized before derived layers execute.

4. Detailed Technical Explanation & Syntax

Implicit super() vs Explicit super(args) Rule

Rule 1: If a subclass constructor does NOT begin with this(...) or super(...), the compiler **automatically inserts super();** (zero-argument call) as its very first statement!

Rule 2 (Classic Parameterized Superclass Trap!): In a multilevel hierarchy (Box -> BoxWeight -> Shipment), if Box ONLY defines a parameterized constructor Box(double w, double h, double d) and has NO no-arg Box(), then BoxWeight MUST explicitly call super(w, h, d)—otherwise javac's implicit super() fails to compile!

Rule 3 (Multilevel Passing Up the Line): As noted in your slides (Shipment -> BoxWeight -> Box), if a superclass constructor requires parameters, ALL subclasses must pass those parameters up the line via super(...), whether or not the subclass needs them itself.

5. Working Principle: Two-Phase Trace (new C() where C extends B extends A)

  1. Invocation Phase (Upward): new C() calls C() -> line 1 super() calls B() -> line 1 super() calls A() -> line 1 calls Object().
  2. Completion Phase (Top-Down): Object() returns -> A() prints & finishes -> B() prints & finishes -> C() prints & finishes.

6. Examination-Ready Diagrams

Diagram 6

Constructor Execution Order in Inheritance

1. Box() [Superclass]Executes body FIRST2. BoxWeight() [Subclass 1]Calls super(), executes SECOND3. Shipment() [Subclass 2]Calls super(), executes LASTPhase 1: super() Calls UpwardPhase 2: Execution Top-Down

Demonstrates the invocation vs completion order in a multilevel hierarchy (Box -> BoxWeight -> Shipment): calls chain upward via super(), while constructor bodies execute top-down from superclass to subclass.

Key Components
  • Call Flow (Upward): new Shipment() calls Shipment(), whose first statement super() invokes BoxWeight(), whose super() invokes Box().
  • Execution Order (Top-Down): Box() body finishes first -> BoxWeight() body finishes second -> Shipment() body finishes last.
Step-by-Step Flow
  1. Step 1: new Shipment(...) enters Shipment constructor.
  2. Step 2: First line super(...) transfers control up to BoxWeight constructor.
  3. Step 3: First line super(...) transfers control up to Box constructor (and Object()).
  4. Step 4: Box initializes width, height, depth and returns.
  5. Step 5: BoxWeight initializes weight and returns.
  6. Step 6: Shipment initializes cost and completes.
How to Draw in KTU Exam
  • Stack Box (top), BoxWeight (middle), Shipment (bottom).
  • Draw upward dashed arrows on the left labeled '1. Constructor Calls (super())'.
  • Draw downward solid arrows on the right labeled '2. Execution Completes (Superclass -> Subclass)'.

7. Complete Java Code Examples & Tracing

Multilevel Constructor Order: `Box -> BoxWeight -> Shipment` TraceShipmentConstructorOrderDemo.java
Complete multilevel example matching the lecture notes (Box -> BoxWeight -> Shipment), printing both call order and volume/cost calculation.
1class BoxModel {
2 private double width, height, depth;
3
4 BoxModel(double w, double h, double d) {
5 System.out.println("1. Executing BoxModel constructor");
6 width = w;
7 height = h;
8 depth = d;
9 }
10
11 double volume() {
12 return width * height * depth;
13 }
14}
15
16class BoxWeightModel extends BoxModel {
17 double weight;
18
19 BoxWeightModel(double w, double h, double d, double m) {
20 super(w, h, d); // Passes dimensions up to BoxModel
21 System.out.println("2. Executing BoxWeightModel constructor");
22 weight = m;
23 }
24}
25
26class ShipmentModel extends BoxWeightModel {
27 double cost;
28
29 ShipmentModel(double w, double h, double d, double m, double c) {
30 super(w, h, d, m); // Passes 4 args up to BoxWeightModel
31 System.out.println("3. Executing ShipmentModel constructor");
32 cost = c;
33 }
34}
35
36public class ShipmentConstructorOrderDemo {
37 public static void main(String[] args) {
38 ShipmentModel ship = new ShipmentModel(10, 20, 15, 12.5, 45.0);
39 System.out.println("Volume: " + ship.volume()
40 + ", Weight: " + ship.weight
41 + ", Shipping Cost: " + ship.cost);
42 }
43}
Expected Output
1. Executing BoxModel constructor
2. Executing BoxWeightModel constructor
3. Executing ShipmentModel constructor
Volume: 3000.0, Weight: 12.5, Shipping Cost: 45.0
Keywords:extendssuperprivatenew
Common Exam & Coding Mistakes
  • Predicting subclass constructor prints BEFORE superclass constructor (3 -> 2 -> 1) — WRONG! Superclass ALWAYS finishes first (1 -> 2 -> 3).
  • Forgetting to pass super(args) in a subclass when the parent lacks a zero-arg constructor.

Real-World Applications

  • GUI frameworks initialize window frame resources (JFrame -> Frame -> Window) bottom-up via constructor chaining before custom child panels draw controls.

Important KTU Exam Points

  • Expect BOTH: a 3-mark output trace (A -> B -> C printing order) AND a 6/9-mark Box -> BoxWeight -> Shipment multilevel question.
  • Draw Diagram 6 clearly showing upward super() calls vs downward execution completion.

Memory Techniques & Revision

  • Calls go UP (Child -> Parent), Bodies run DOWN (Parent -> Child)!

Common Pitfalls to Avoid

  • Assuming omitting super() skips the parent constructor—Java automatically inserts super() silently!

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: In Java inheritance, constructors always complete execution in order of derivation: from the topmost superclass down to the deepest subclass.

  • Because super(...) (either written explicitly or inserted implicitly by javac) is always the first statement executed in a subclass constructor, control climbs up to the root superclass before any subclass body executes.
  • In Shipment -> BoxWeight -> Box, calling new Shipment(...) executes Box first, then BoxWeight, and finally Shipment.
Exam Diagram Note: Draw Diagram 6 (Box -> BoxWeight -> Shipment) with upward super() arrows and downward execution sequence.

Quick Understanding Check

1. Given class A { A(){print("A");} }, class B extends A { B(){print("B");} }, class C extends B { C(){print("C");} }, what does new C() print?