Java Reference
In-Depth Information
other data field must be declared first, as shown in Figure 10.1b. For consistency, this topic
declares data fields at the beginning of the class.
You can declare a class's variable only once, but you can declare the same variable name in
a method many times in different nonnesting blocks.
If a local variable has the same name as a class's variable, the local variable takes
precedence and the class's variable with the same name is
hidden
. For example, in the fol-
lowing program,
x
is defined both as an instance variable and as a local variable in the
method.
hidden variables
public class
F {
private int
x =
0
;
// Instance variable
private int
y =
0
;
public
F() {
}
public void
p() {
int
// Local variable
System.out.println(
"x = "
+ x);
System.out.println(
"y = "
+ y);
x =
1
;
}
}
What is the printout for
f.p()
, where
f
is an instance of
F
? The printout for
f.p()
is
1
for
x
and
0
for
y
. Here is why:
■
x
is declared as a data field with the initial value of
0
in the class, but it is also
declared in the method
p()
with an initial value of
1
. The latter
x
is referenced in the
System.out.println
statement.
■
y
is declared outside the method
p()
, but
y
is accessible inside the method.
Tip
To avoid confusion and mistakes, do not use the names of instance or static variables as
local variable names, except for method parameters.
✓
✓
10.4
What is the output of the following program?
Check
Point
public class
Test {
private static int
i =
0
;
private static int
j =
0
;
public static void
main(String[] args) {
int
i =
2
;
int
k =
3
;
{
int
j =
3
;
System.out.println(
"i + j is "
+ i + j);
}
k = i + j;
System.out.println(
"k is "
+ k);
System.out.println(
"j is "
+ j);
}
}