ThisAssignable

Misconception:

It is legal to assign a value to this (for example in the constructor).

Incorrect

One can assign to this

Correct

One cannot assign to this

Correction
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.

Symptoms
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;
}

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.