Java Reference
In-Depth Information
Listing 6-13.
Using the this Keyword to Refer to an Instance Variable Whose Name Is Hidden by a Local Variable
// ThisTest6.java
package com.jdojo.cls;
public class ThisTest6 {
int num = 1982; // An instance variable
void printNum(int num) {
System.out.println("Parameter num: " + num);
System.out.println("Instance variable num: " + this.num);
}
public static void main(String[] args) {
ThisTest6 tt6 = new ThisTest6();
tt6.printNum(1969);
}
}
Parameter num: 1969
Instance variable num: 1982
The output of
ThisTest6
shows the expected result. If you do not want to use the keyword
this
, you can rename
the parameter of the
printNum()
method, like so:
void printNum(int numParam) {
System.out.println("Parameter num: " + numParam);
System.out.println("Instance variable num: " + num);
}
Once you rename the parameter to something other than
num
, the
num
instance variable is no longer hidden
inside the body of the
printNum()
method, and therefore you can refer to it using its simple name.
You can use the keyword
this
to refer to the instance variable
num
inside the
printNum()
method even if it
is not hidden as shown below. However, using the keyword
this
in the following case is a matter of choice, not a
requirement.
void printNum(int numParam) {
System.out.println("Parameter num: " + numParam);
System.out.println("Instance variable num: " + this.num);
}
In the previous example, you saw that use of the keyword
this
is necessary to access instance variables when
the instance variable name is hidden. You can avoid using the keyword
this
in such circumstances by renaming the
variable that hides the instance variable name, or renaming the instance variable itself. Sometimes it is easier to keep
the variable names the same, as they represent the same thing. This topic uses the convention of using the same name
for instance variables and local variables if they represent the same thing in the class. For example, the following code
is very common:
public class Student {
private int id; // An instance variable