
π Day 10 of My Automation Journey β Tricky Constructor Questions (Inheritance in Java)
Discussing tricky scenarios, letβs break this clearly and powerfully πͺ β 1οΈβ£ Golden Rule of Constructors in Inheritance When a child object is created: π Parent constructor executes first π Then Child constructor executes Because every child class constructor implicitly or explicitly calls super() . π― Scenario 1: Parent has NO-ARG constructor class Parent { Parent() { System.out.println("Parent No-Arg Constructor"); } } class Child extends Parent { Child() { System.out.println("Child No-Arg Constructor"); } public static void main(String[] args) { new Child(); } } πΉ Output: Parent No-Arg Constructor Child No-Arg Constructor β Java automatically inserts super(); π― Scenario 2: Parent has ONLY Parameterized Constructor class Parent { Parent(int x) { System.out.println("Parent Parameterized Constructor"); } } class Child extends Parent { Child() { System.out.println("Child Constructor"); } } β Compile Time Error! Why? Because Java tries to insert: super(); // default But Parent does NOT ha
Continue reading on Dev.to
Opens in a new tab




