Java Reference
In-Depth Information
course, you could have kept the name of the formal parameters as before and still used the
reference
this
as shown in the code.
Similarly, explicitly using the reference
this
, you can write the definition of the method
incrementSeconds
as follows:
public void
incrementSeconds()
{
this
.sec++;
if
(
this
.sec > 59)
{
this
.sec = 0;
this
.incrementMinutes();
//increment minutes
}
}
In addition to explicitly referring to the instance variables and methods of an object, the
reference
this
has another use—to implement cascaded method calls. We explain this
with the help of an example.
In Example 8-8, we designed the
class
Person
to implement a person's name in a
program. Here, we extend the definition of the
class
Person
to individually set a
person's first name and last name, and then return a reference to the object, using
this
.
The following code is the extended definition of the
class
Person
. (The methods
setFirstName
and
setLastName
are added to this definition of the
class
Person
.)
public class
Person
{
private
String firstName;
//store the first name
private
String lastName;
//store the last name
//Default constructor;
//Initialize firstName and lastName to empty string.
//Postcondition: firstName = ""; lastName = "";
public
Person()
{
firstName = "";
lastName = "";
}
//Constructor with parameters
//Set firstName and lastName according to the parameters.
//Postcondition: firstName = first; lastName = last;
public
Person(String first, String last)
{
setName(first, last);
}
Search WWH ::
Custom Search