Java Reference
In-Depth Information
A related concept is known as
shadowing
in which a local variable has the
same name as a member variable. For example,
public class Shadow {
int x = 1;
void someMethod () {
int x = 2;
...
}
}
Here the
x
inside
someMethod()
shadows
the member variable
x
in the class
definition. The local value 2 is used inside
someMethod()
while the member
variable value 1 is used elsewhere. Such usage is often a mistake, and can certainly
lead to hard-to-find bugs. This technique is not recommended. In fact, the variable
naming conventions explained in Chapter 5 are designed to prevent accidental
shadowing of member variables.
We can also explicitly reference instance variables in the current object with
the
this
reference. The code below illustrates a common technique to distinguish
parameter variables from instance or class variables:
public class
A
{
int x;
void doSomething (int x) {
// x holds the value passed in the parameter list.
// To access the instance variable x we must
// specify it with 'this'.
this.x = x;
}
}
Here the local parameter variable shadows the instance variable with the same
name. However, the
this
reference in
this.x
explicitly indicates that the left-
hand side of the equation refers to the instance variable
x
instead of the local
variable
x
from the parameter list.
4.3 More about constructors
In Chapter 3 we discussed the basics of constructors, including the overloading
of constructors. Here we discuss some additional aspects of constructors.
4.3.1
this()
In addition to the
this
reference, there is also a special method named
this()
which invokes constructors from within other constructors. When a class holds
Search WWH ::
Custom Search