Complete the code to call the parent class constructor from the child class.
class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { [1]; System.out.println("Child constructor"); } }
In Java, super() calls the parent class constructor.
Complete the code to call another constructor in the same class.
class Example { Example() { this(10); System.out.println("Default constructor"); } Example(int x) { System.out.println("Constructor with value: " + [1]); } }
The parameter name x is used to print the passed value.
Fix the error in the constructor chaining code.
class Test { Test() { [1]; System.out.println("No-arg constructor"); } Test(int a) { System.out.println("Constructor with int: " + a); } }
Use this(5) to call another constructor in the same class with an int argument.
Fill both blanks to complete the constructor chaining and print the correct messages.
class Base { Base() { System.out.println("Base constructor"); } } class Derived extends Base { Derived() { [1]; System.out.println("Derived constructor"); } Derived(int x) { System.out.println("Derived with int: " + [2]); } }
The no-arg constructor calls this(5) to chain to the int constructor, which prints the parameter x.
Fill all three blanks to create a class with constructor chaining and parent constructor call.
class Alpha { Alpha() { System.out.println("Alpha default"); } Alpha(String msg) { System.out.println(msg); } } class Beta extends Alpha { Beta() { [1]; System.out.println("Beta default"); } Beta(String msg) { [2]; System.out.println("Beta with message: " + [3]); } }
The no-arg constructor calls this("Hello") to chain to the string constructor.
The string constructor calls super(msg) to call the parent constructor with the message.
Finally, it prints the message using the parameter msg.