DRAFT
ThisInConstructorIsNull
Misconception:
In a constructor this
is still null
.
It will only be set after the constructor finishes.
Incorrect
In a constructor, this is null
Correct
In a constructor, this is never null
CorrectionHere is what's right.
Here is what's right.
Already at the beginning of the constructor,
this
refers to the new (still uninitialized) object.
If this
was null
in the constructor,
one couldn’t initialize the object,
because one would not have any reference to the object.
SymptomsHow do you know your students might have this misconception?
How do you know your students might have this misconception?
The following exam question, while having the goal of checking whether students understand that constructors don’t return anything, also brings up this misconception:
Is the constructor implementation in the following class correct? Explain!
public class C {
public C() {
return this;
}
}
Example answer: “No, because this does not refer to anything.”
Language
Java
Concepts
Expressible In
StackHeapGlobalDiagram
stack frame of a constructor with thisExpressionAsTree
expression involving this