Java Reference
In-Depth Information
simply by using the
ClassName.staticVariable
reference. A hidden instance variable
can be accessed by using the keyword
this
, as shown in FigureĀ 9.21a.
public class
F {
private int
i =
5
;
private static double
k =
0
;
Suppose that f1 and f2 are two objects of F.
Invoking f1.setI(
10
) is to execute
this
.i =
10
,
where
this
refers f1
public void
setI(
int
i) {
this
.i = i;
Invoking f2.setI(
45
) is to execute
this
.i =
45
,
where
this
refers f2
}
public static void
setK(
double
k) {
F.k = k;
Invoking F.setK(
33
) is to execute
F.k =
33
.
setK is a static method
}
// Other methods omitted
}
(a)
(b)
F
IGURE
9.21
The keyword
this
refers to the calling object that invokes the method.
The
this
keyword gives us a way to reference the object that invokes an instance method.
To invoke
f1.setI(10)
,
this.i = i
is executed, which assigns the value of parameter
i
to
the data field
i
of this calling object
f1
. The keyword
this
refers to the object that invokes the
instance method
setI
, as shown in FigureĀ 9.21b. The line
F.k = k
means that the value in param-
eter
k
is assigned to the static data field
k
of the class, which is shared by all the objects of the class.
9.14.2 Using
this
to Invoke a Constructor
The
this
keyword can be used to invoke another constructor of the same class. For example,
you can rewrite the
Circle
class as follows:
public class
Circle {
private double
radius;
public
Circle(
double
radius) {
this
.
radius = radius;
}
The
this
keyword is used to reference the hidden
data field radius of the object being constructed.
public
Circle() {
this
(
1.0
);
}
The
this
keyword is used to invoke another
constructor.
...
}
The line
this(1.0)
in the second constructor invokes the first constructor with a
double
value argument.
Note
Java requires that the
this(arg-list)
statement appear first in the constructor
before any other executable statements.
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 a
constructor with more arguments using
this(arg-list)
. This syntax often simpli-
fies coding and makes the class easier to read and to maintain.
Search WWH ::
Custom Search