Java Reference
In-Depth Information
void printNum() {
System.out.println("Instance variable num: " + num);
}
public static void main(String[] args) {
ThisTest4 tt4 = new ThisTest4();
tt4.printNum();
}
}
Instance variable num: 1982
Let's modify the printNum() method of the ThisTest4 class so it accepts an int parameter. Let's name the
parameter num . Listing 6-12 has the modified code for the printNum() method as part of the ThisTest5 class.
Listing 6-12. Variables Name Hiding
// ThisTest5.java
package com.jdojo.cls;
public class ThisTest5 {
int num = 1982; // An instance variable
void printNum(int num) {
System.out.println("Parameter num: " + num);
System.out.println("Instance variable num: " + num);
}
public static void main(String[] args) {
ThisTest5 tt5 = new ThisTest5();
tt5.printNum(1969);
}
}
Parameter num: 1969
Instance variable num: 1969
The output of the ThisTest5 class indicates that the printNum() method is using its parameter num when you use
the simple name num inside its body. This is an example of name hiding, where the local variable (method parameter
is considered a local variable) num hides the name of the instance variable num inside the printNum() method's body.
In the printNum() method, the simple name num refers to its parameter num , not the instance variable num . In this case,
you must use the keyword this to qualify the num variable if you want to refer to the num instance variable inside the
printNum() method. Using this.num is the only way you can refer to the instance variable from inside the printNum()
method, as long you keep the parameter name as num . Another way is to rename the parameter to something other
than num , for example, numParam or newNum . Listing 6-13 shows how to use the keyword this to refer to the num
instance variable inside the printNum() method.
 
Search WWH ::




Custom Search