ThisNoExpression
In a method body, this
is not an expression.
It can only be used for the specific purpose
to distinguish instance variable accesses from local variable accesses,
which is useful if instance variables have the same name as local variables.
The name this is not an expression
Even the name this on its own is an expression
CorrectionHere is what's right.
this
is an expression that evaluates to an object reference. The type of this
is the enclosing class.
class Count {
private final int value;
public Count(final int value) {
this.value = value;
}
public Count countDownIfPossible() {
if (value>0) {
return new Count(value-1);
} else {
return this; // perfectly fine: type of this is Count
}
}
OriginWhere could this misconception come from?
Students initially only see this
being used to access instance variables
(e.g., this.x = 5;
).
Thus they develop the idea that this.
is a magical prefix
with the sole purpose of qualifying instance variable accesses.
SymptomsHow do you know your students might have this misconception?
Students may believe that this
on its own doesn’t have any meaning.
They might express statements that treat pieces of code
like return this
or m(this)
or x = this
as wrong.
Another simple related symptom shows when they do not realize
that this.m()
is a proper way to invoke a method m()
on the same object.
ValueHow can you build on this misconception?
This misconception provides an opportunity to discuss the concept of expressions and to make students aware of the power of the idea of composing expressions from other expressions.