Return to site

☕🎓JAVA CERTIFICATION QUESTION: super and this

· java,ocp

Given the following two classes:

Which constructor can be added to the Hotel class without causing compilation errors? Choose two.

* Hotel() { super(nb); }

* Hotel() { super(nextBuilding); }

* Hotel() { super(super); }

* Hotel() { super(this); }

* Hotel() { super(null); }

* Hotel() { super(new Hotel() {}); }

 

#java #certificationquestion #ocp

 

Answer:

* Hotel() { super(null); }

* Hotel() { super(new Hotel() {}); }

During constructor execution, `super(...)` and `this(...)` ensure that object initialization starts from the `Object` class and progresses from the parent to the child aspects, with each level executing its own initializers and constructors before passing control to the next subclass level down.

Two important points to note:

1) The constructor must start with a call to this(...) or super(...), with super() added automatically if neither is explicitly coded.

2) The argument list in these calls must not refer to this directly or indirectly using an unqualified identifier. The use of the super prefix, which is similar to this but with a different type, is also not allowed.

Considering the previous statements, let's discuss each answer options:

"Hotel() { super(nb); }", the actual parameter to the super call is nb.

This can be resolved only as an implicit reference to this.nb and, as such, the constructor is not valid so this option is incorrect.

"Hotel() { super(nextBuilding); }" fails by the same reasoning because the identifier nextBuilding is resolved as this.nextBuilding and is not valid as an argument to the super call.

"Hotel() { super(super); }" is incorrect for two reasons.

First, super is not usable as a standalone reference; it can be used only as a prefix.

Second, as already mentioned, super can’t appear in the argument list of this(...) or super(...).

"Hotel() { super(this); }" is similarly incorrect because this cannot appear in the argument list of this(...) or super(...).

"Hotel() { super(null); }" is correct.

While it might not be helpful from a semantic perspective, null is a valid parameter to pass to this(...) or super(...) provided there is a target constructor that takes an argument of reference type.

"Hotel() { super(new Hotel() {}); }" is also correct because it shows valid syntax constructing an anonymous subclass of Hotel.

Such an expression is acceptable as an argument to the super(...) invocation and will delegate to the Building constructor of the form Building(Building nb).