Consider the following Java code with inheritance and constructors. What will be printed when new Child() is executed?
class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { System.out.println("Child constructor"); } } public class Test { public static void main(String[] args) { new Child(); } }
Remember that the parent constructor runs before the child constructor.
When creating a Child object, Java first calls the Parent constructor implicitly, then the Child constructor. So the output is Parent constructor followed by Child constructor.
Analyze the constructor calls and determine the output.
class A { A() { this(5); System.out.println("A no-arg"); } A(int x) { System.out.println("A int: " + x); } } public class Test { public static void main(String[] args) { new A(); } }
Look at how this() calls another constructor before printing.
The no-argument constructor calls the one-argument constructor first, which prints A int: 5. After that finishes, it prints A no-arg.
Examine the code and identify the error that occurs when compiling.
class B { B() { this(); System.out.println("B no-arg"); } } public class Test { public static void main(String[] args) { new B(); } }
Check how this() is used inside the constructor.
The constructor calls itself recursively with this() without a base case, causing a compile-time error for recursive constructor invocation.
Given the classes below, what will be printed when new C() is executed?
class A { A() { System.out.println("A constructor"); } } class B extends A { B() { System.out.println("B constructor"); } } class C extends B { C() { super(); System.out.println("C constructor"); } } public class Test { public static void main(String[] args) { new C(); } }
Remember the order of constructor calls in inheritance.
When C() is called, it calls B() via super(), which implicitly calls A(). So the order is A, then B, then C.
Consider the following code. How many times is the constructor of class A executed when new D() is called?
class A { A() { System.out.println("A constructor"); } } class B extends A { B() { System.out.println("B constructor"); } } class C extends A { C() { System.out.println("C constructor"); } } class D extends B { D() { super(); System.out.println("D constructor"); } } public class Test { public static void main(String[] args) { new D(); } }
Trace the inheritance chain and constructor calls carefully.
Class D extends B, which extends A. When D() is called, it calls B(), which calls A(). Class C is unrelated here and its constructor is not called. So A() runs once.