Constructor Calling Order & Execution in Multilevel 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.
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**!
super() explicitly or let javac insert super() automatically!3. Essential Exam Definitions
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)
- Invocation Phase (Upward):
new C()callsC()-> line 1super()callsB()-> line 1super()callsA()-> line 1 callsObject(). - Completion Phase (Top-Down):
Object()returns ->A()prints & finishes ->B()prints & finishes ->C()prints & finishes.
6. Examination-Ready Diagrams
Constructor Execution Order in Inheritance
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.
- Call Flow (Upward):
new Shipment()callsShipment(), whose first statementsuper()invokesBoxWeight(), whosesuper()invokesBox(). - Execution Order (Top-Down):
Box()body finishes first ->BoxWeight()body finishes second ->Shipment()body finishes last.
- Step 1:
new Shipment(...)entersShipmentconstructor. - Step 2: First line
super(...)transfers control up toBoxWeightconstructor. - Step 3: First line
super(...)transfers control up toBoxconstructor (andObject()). - Step 4:
Boxinitializeswidth, height, depthand returns. - Step 5:
BoxWeightinitializesweightand returns. - Step 6:
Shipmentinitializescostand completes.
- 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
Box -> BoxWeight -> Shipment), printing both call order and volume/cost calculation.| 1 | class 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 | |
| 16 | class 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 | |
| 26 | class 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 | |
| 36 | public 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 | } |
1. Executing BoxModel constructor 2. Executing BoxWeightModel constructor 3. Executing ShipmentModel constructor Volume: 3000.0, Weight: 12.5, Shipping Cost: 45.0
extendssuperprivatenew- 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 -> Cprinting order) AND a 6/9-markBox -> BoxWeight -> Shipmentmultilevel 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 insertssuper()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 byjavac) 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, callingnew Shipment(...)executesBoxfirst, thenBoxWeight, and finallyShipment.
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?