Java Reference
In-Depth Information
Simple Cases with Class Parameters
Methods can have parameters of a class type. Parameters of a class type are more subtle
and more powerful than parameters of a primitive type. We will discuss parameters
of class types in detail in Chapter 5 . In the meantime, we will occasionally use a class
type parameter in very simple situations. For these cases, you do not need to know
any details about class type parameters except that, in some sense or other, the class
argument is plugged in for the class parameter.
The
this
Parameter
As we noted earlier, if
today
is of type
DateSecondTry
(see Display 4.2 ), then
today.writeOutput();
is equivalent to
System.out.println(today.month + " " + today.day
+ ", " + today.year);
This is because, although the definition of
writeOutput
reads
public void
writeOutput()
{
System.out.println(month + " " + day + ", " + year);
}
it really means
public void
writeOutput()
{
System.out.println(<
the calling object
>.month + " "
+ <
the calling object
>.day + ", " + <
the calling object
>.year);
}
The instance variables are understood to have
<
the calling object
>.
in front of them.
Sometimes it is handy, and on rare occasions even necessary, to have an explicit name
for the calling object. Inside a Java method definition, you can use the keyword
this
as
a name for the calling object. So, the following is a valid Java method definition that is
equivalent to the one we are discussing:
public void
writeOutput()
{
System.out.println(
this
.month + " " +
this
.day
+ ", " +
this
.year);
}
The definition of
writeOutput
in Display 4.2 could be replaced by this completely
equivalent version. Moreover, this version is in some sense the true version. The version