Chapter 5, "
Instance and static variables in a class are referred to as the
class's variables
or
data fields
. A variable defined inside a method is referred to as a local variable. The scope of a class's variables is the entire class, regardless of where the variables are declared. A class's variables and methods can be declared in any order in the class, as shown in Figure 7.18(a). The exception is when a data field is
You can declare a class's variable only once, but you can declare the same variable
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 following program, x is defined as an instance variable and as a local variable in the method.
class Foo { int x = ; // instance variable int y = ; Foo() { } void p() { int x = 1 ; // local variable System.out.println( "x = " + x); System.out.println( "y = " + y); } }
What is the printout for f.p() , where f is an instance of Foo ? The printout for f.p() is 1 for x and for y . Here is why:
x is declared as a data field with the initial value of in the class, but is also defined 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 is accessible inside it.
Tip
|
|
As demonstrated in the example, it is easy to make mistakes. To avoid confusion, do not declare the same variable name twice in a class, except for method parameters. |
Sometimes you need to reference a class's
hidden variable
in a method. For example, a property name is often used as the parameter
The line this.i = i means "assign the value of parameter i to the data field i of the calling object." The keyword this serves as a proxy for the object that invokes the instance method setI , as shown in Figure 7.19(b). The line Foo.k = k means that the value in parameter k is assigned to the static data field k of the class, which is shared by all the objects of the class.
The keyword
this
can also be used inside a constructor to invoke another constructor of the same class. For example, you can redefine the
Circle
class as
The line this(1.0) invokes the constructor with a double value argument in the class.
Tip
|
|
If a class has multiple constructors, it is better to implement them using
this(arg-list)
as much as possible. In general, a constructor with no or fewer arguments can invoke the constructor with more arguments using
this(arg-list)
. This often
|
Note
|
|
Java requires that the this(arg-list) statement appear first in the constructor before any other statements. |