Return to site

☕🎓JAVA CERTIFICATION QUESTION: super & this

· java,ocp

Given the following two classes:

01: abstract class SupA {

02: SupA() { this(null); }

03: SupA(SubA s) {this.init();}

04: abstract void init();

05: }

06: class SubA extends SupA {

07: void init() {System.out.print("SubA");}

08: }

 

Which statement is correct if you try to compile the code and create an instance of SubA? Choose one.

* Compilation fails at line 02.

* Compilation fails at line 03.

* A runtime exception occurs at line 02.

* A runtime exception occurs at line 03.

* SubA is printed.

* SubASubA is printed.

#java #certificationquestion #ocp

 

 

 

Answer: SubA is printed.

Note that all constructors start with one of three code elements.

First, there is an implicit call to super() with no arguments.

This is followed by either an explicit call to super(...),

which may take arguments, or by a call to this(...),

which, again, may take arguments.

Strictly, evaluation of any actual parameters to these calls executes before those delegating calls.

The class SupA has two constructors.

The one on line 02 delegates to the one on line 03 using this(null),

while the one on line 03 has an implicit call to super().

The class SubA has no explicit constructors;

therefore, the compiler gives it an implicit constructor, which delegates using super().

From that outline, consider the flow of construction and initialization of an instance of SubA.

1. The newly allocated object is passed as the implicit this argument into the implicit constructor for SubA.

2. That constructor immediately delegates—using super()—to the zero-argument constructor for SupA.

3. That constructor in turn immediately delegates to the one-argument constructor for SupA on line 03 using the explicit call this(null).

4. The body of the constructor on line 03 begins with an implicit call to super() that was generated by the compiler.

5. That call passes control up to the zero-argument constructor of java.lang.Object.

6. The constructor body calls this.init();, which invokes the implementation on line 07 and prints the message SubA.

Notice that in the description above, the message SubA was printed exactly once.