Java Reference
In-Depth Information
The output of the application is the following:
The array: [ 4 5 6 7 8 9 10 11 12 13 ]
The main() method in this class tests the makeRange() method by calling it with the
arguments of 4 and 13. The method creates an empty integer array and uses a for loop to
fill the new array with values from 4 through 13 in lines 5-7.
The this Keyword
In the body of a method definition, there are times you might need to refer to the object
to which the method belongs. This can be done to use that object's instance variables and
to pass the current object as an argument to another method.
To refer to the object in these cases, use the this keyword where you normally would
refer to an object's name.
The this keyword refers to the current object, and you can use it anywhere a reference
to an object might appear: in dot notation, as an argument to a method, as the return
value for the current method, and so on. The following are some examples of using this :
t = this.x; // the x instance variable for this object
this.resetData(this); // call the resetData method, defined in
// this class, and pass it the current
// object
return this; // return the current object
In many cases, you might not need to explicitly use the this keyword because it is
assumed. For instance, you can refer to both instance variables and method calls defined
in the current class simply by name because the this is implicit in those references.
Therefore, you could write the first two examples as the following:
t = x; // the x instance variable for this object
resetData(this); // call the resetData method, defined in this
// class
NOTE
The viability of omitting the this keyword for instance variables
depends on whether variables of the same name are declared in
the local scope. You see more on this subject in the next section.
Because this is a reference to the current instance of a class, use it only inside the body
of an instance method definition. Class methods—which are declared with the static
keyword—cannot use this .
Search WWH ::




Custom Search