Java Reference
In-Depth Information
You can also qualify a class variable with a class name, as shown in the CorrectThisTest3 class:
public class CorrectThisTest3 {
static int varU = 555;
static int varV = varU;
static int varW = CorrectThisTest3.varU;
}
Most of the time you can use the simple name of instance and class variables within the class in which they are
declared. You need to qualify an instance variable with the keyword this and a class variable with the class name only
when the instance variable or the class variable is hidden by another variable with the same name.
Tip
Let's consider the following snippet of code for the ThisTest3 class:
public class ThisTest3 {
int varU = 555;
static int varV = varU; // A compile-time error
static int varW = varU; // A compile-time error
}
When you compile the ThisTest3 class, you will receive the following error:
"ThisTest3.java": non-static variable varU cannot be referenced from a static context at line 3,
column 21
"ThisTest3.java": non-static variable varU cannot be referenced from a static context at line 4,
column 21
The compiler error is the same in kind, although differently phrased, compared to the compiler error that you
received for the ThisTest2 class. Last time, it complained about using the keyword this . This time, it complained
about using the instance variable varU . Both the keyword this and the varU exist in the context of an instance. They
do not exist in the context of a class. Whatever exists in the context of an instance cannot be used in the context of a
class. However, whatever exists in the context of a class can always be used in the context of an instance. The instance
variable declaration and initialization occurs in the context of an instance. In the ThisTest3 class, varU is an instance
variable and it exists only in the context of an instance. The varV and varW in ThisTest3 class are class variables and
they exist only in the context of a class. This is the reason that the compiler complained.
Let's consider the code for the ThisTest4 class, shown in Listing 6-11. It declares an instance variable, num , and
an instance method, printNum() . In the printNum() instance method, it prints the value of the instance variable num .
In its main() method, it creates an instance of the ThisTest4 class and invokes the printNum() method on it. The
output of the ThisTest4 class shows the expected result.
Listing 6-11. An Example of Using the Simple Name of an Instance Variable in an Instance Method
// ThisTest4.java
package com.jdojo.cls;
public class ThisTest4 {
int num = 1982; // An instance variable
 
 
Search WWH ::




Custom Search