Back to articles
πŸš€ Day 10 of My Automation Journey – Tricky Constructor Questions (Inheritance in Java)

πŸš€ Day 10 of My Automation Journey – Tricky Constructor Questions (Inheritance in Java)

via Dev.tobala d kaveri

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

Read Full Article
3 views

Related Articles