Master Core Java Step-by-Step!
Subscribe to Ram N Java for deep-dive compiler insights, clear logic explanations, and coding tips!
Subscribe Now on YouTubeWhat Happens Behind the Scenes During Inheritance?
In Java, when you instantiate a subclass, the parent class constructor always runs before the child constructor logic executes. Even if you never explicitly write a call to super(), Java handles constructor chaining seamlessly under the hood.
Understanding how the Java compiler injects default calls gives you total clarity on how objects are initialized across your class hierarchy.
What the Java Compiler Automatically Injects
When compiling your Java code, the compiler enforces strict rules around constructors:
- Automatic Default Constructor: If you do not write any constructor in a class, the compiler creates an empty, no-argument constructor for you.
- Automatic super() Insertion: If a constructor does not explicitly start with
super(...)orthis(...), the compiler addssuper();as the first instruction. - Top-Down Initialization: Because each child constructor delegates upward first, the topmost parent (all the way up to
Object) initializes before any child class code runs.
Source Code vs. Compiler View
What You Write:
class Vehicle {
Vehicle() {
System.out.println("Vehicle Created");
}
}
class Bike extends Vehicle {
Bike() {
System.out.println("Bike Created");
}
}
What the Java Compiler Compiles:
class Bike extends Vehicle {
Bike() {
super(); // Automatically added by compiler!
System.out.println("Bike Created");
}
}
When Does This Cause a Compilation Error?
The compiler only automatically adds super(); without arguments. This leads to a compilation error if:
- The parent class defines only parameterized constructors (meaning no default no-argument constructor exists).
- The child class attempts to invoke
super();implicitly or explicitly without parameters.
To fix this, either keep a no-argument constructor in your parent class or pass the required arguments explicitly using super(arg1, arg2).
No comments:
Post a Comment