ThisAssignable
Incorrect
One can assign to this
Correct
One cannot assign to this
CorrectionHere is what's right.
Here is what's right.
You cannot assign to this
.
this
is a special read-only variable
that gets automatically set up by Java
whenever a constructor or an instance method is invoked.
It always points to the object on which the method was invoked,
or to the object the constructor is initializing.
SymptomsHow do you know your students might have this misconception?
How do you know your students might have this misconception?
We have observed this misconception in constructors and in recursive traversals over recursive data structures.
Constructors
This misconception manifests itself in code like the following:
public class C {
public C() {
this = new C(); // incorrect
}
//...
}
Recursive Traversals
The following example comes from code to traverse a linked list, where the student used a while loop iterating over all nodes, and used this as the variable to hold the reference to the current node.
while (this != null) {
// process this node
this = this.tail;
}
Language
Java
Concepts
Expressible In
Related Misconceptions
ConstructorAllocates
When assigning to this in constructorConstructorReturnsObject
MaybeThisCanBeNull
MaybeThisInConstructorIsNull
Maybe