Java Reference
In-Depth Information
the object through which the method is invoked. In our example, that object is a
Circle .
The bodies of the area() and circumference() methods both
use the class field PI . We saw earlier that class methods can
use only class fields and class methods, not instance fields or
methods. Instance methods are not restricted in this way: they
can use any member of a class, whether it is declared static
or not.
How the this Reference Works
The implicit this parameter is not shown in method signatures because it is usually
not needed; whenever a Java method accesses the instance fields in its class, it is
implicit that it is accessing fields in the object referred to by the this parameter. The
same is true when an instance method invokes another instance method in the same
class—it's taken that this means “call the instance method on the current object.”
m
g
O
However, you can use the this keyword explicitly when you want to make it clear
that a method is accessing its own fields and/or methods. For example, we can
rewrite the area() method to use this explicitly to refer to instance fields:
public double area () { return Circle . PI * this . r * this . r ; }
This code also uses the class name explicitly to refer to class field PI . In a method
this simple, it is not normally necessary to be quite so explicit. In more complicated
cases, however, you may sometimes find that it increases the clarity of your code to
use an explicit this where it is not strictly required.
In some cases, the this keyword is required, however. For example, when a method
parameter or local variable in a method has the same name as one of the fields of
the class, you must use this to refer to the field, because the field name used alone
refers to the method parameter or local variable.
For example, we can add the following method to the Circle class:
public void setRadius ( double r ) {
this . r = r ; // Assign the argument (r) to the field (this.r)
// Note that we cannot just say r = r
}
Some developers will deliberately choose the names of their method arguments in
such a way that they don't clash with field names, so the use of this can largely be
avoided.
Finally, note that while instance methods can use the this keyword, class methods
cannot. This is because class methods are not associated with individual objects.
Search WWH ::




Custom Search