Java Reference
In-Depth Information
What Is this?
Java has a keyword called
this
. It is a reference to the current instance of a class. It can be used only in the context of
an instance. It can never be used in the context of a class because it means the current instance, and no instance exists
in the context of a class.
The keyword
this
is used in many contexts. I will cover most of its uses in this chapter, not necessarily in this
section. However, you need to note that when it appears in Java code, it means the current instance of the class for
which the code is being executed.
Let's consider the following snippet of code that declares a class
ThisTest1
:
public class ThisTest1 {
int varA = 555;
int varB = varA; // Assign value of varA to varB
int varC = this.varA; // Assign value of varA to varC
}
The
ThisTest1
class declares three instance variables:
varA
,
varB
, and
varC
. The instance variable
varA
is
initialized to 555. The instance variable
varB
is initialized to the value of
varA
, which is 555. The instance variable
varC
is initialized to the value of
varA
, which is 555. Note the difference in initialization expressions for
varB
and
varC
.
I used unqualified
varA
when I initialized
varB
. I used
this.varA
when I initialized
varC
. However, the effect is the
same. Both
varB
and
varC
are initialized with the value of
varA
. When I use
this.varA
, it means the value of
varA
for
the current instance, which is 555. In this simple example, it was not necessary to use the keyword
this
. In the above
case, the unqualified
varA
refers to the
varA
for the current instance. However, there are some cases where you must
use the keyword
this
. I will discuss such cases shortly.
Since the use of the keyword
this
is illegal in the context of a class, you cannot use it when you initialize a class
variable, like so:
// Would not compile
public class ThisTest2 {
static int varU = 555;
static int varV = varU;
static int varW = this.varU; // A compile-time error
}
When you compile the code for the class
ThisTest2
, you receive the following compiler error:
"ThisTest2.java": non-static variable this cannot be referenced from a static context at line 4,
column 21
The compiler error is loud and clear that you cannot use the keyword
this
in a static context. Note that static and
non-static words are synonymous with “class” and “instance” terms in Java. Static context is the same as class context
and non-static context is the same as instance context. The above code can be corrected by removing the qualifier
this
from the initialization expression for
varW
, as follows:
public class CorrectThisTest2 {
static int varU = 555;
static int varV = varU;
static int varW = varU; // Ok
}