Java Reference
In-Depth Information
Tip
To avoid confusion and mistakes, do not use the names of instance or static variables as
local variable names, except for method parameters.
9.31
✓
✓
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);
}
}
The keyword
this
refers to the object itself. It can also be used inside a constructor to
invoke another constructor of the same class.
Key
Point
The
this
keyword
is the name of a reference that an object can use to refer to itself. You can
use the
this
keyword to reference the object's instance members. For example, the following
code in (a) uses
this
to reference the object's
radius
and invokes its
getArea()
method
explicitly. The
this
reference is normally omitted, as shown in (b). However, the
this
reference is needed to reference hidden data fields or invoke an overloaded constructor.
this
keyword
public class
Circle {
private double
radius;
public class
Circle {
private double
radius;
...
...
public double
getArea() {
return this
.
radius
*
this
.
radius * Math.PI;
}
public double
getArea() {
return
radius * radius * Math.PI;
Equivalent
}
public String
toString() {
return
"radius: "
+
this
.
radius
+
"area: "
+
this
.getArea() ;
public String
toString() {
return
"radius: "
+ radius
+
"area: "
+ getArea() ;
}
}
}
}
(a)
(b)
9.14.1 Using
this
to Reference Hidden Data Fields
The
this
keyword can be used to reference a class's
hidden data fields
. For example, a data-
field name is often used as the parameter name in a setter method for the data field. In this
case, the data field is hidden in the setter method. You need to reference the hidden data-field
name in the method in order to set a new value to it. A hidden static variable can be accessed
hidden data fields
Search WWH ::
Custom Search