Java Reference
In-Depth Information
to whatever object that computePay() was invoked on, which in every case is
the
this
reference.
The computePay() method actually looks like the following:
public double computePay()
{
return this.salary/52;
}
Notice that the
this
reference and the dot operator were prefixed to salary.
The compiler adds the
this
reference for you if you do not explicitly add it
yourself. You can add the
this
reference if you like, or you can simply let the
compiler do it for you.
For example, in the Employee class, the mailCheck() method accesses the
name and address fields. In each case, the
this
reference is used, whether you
add it to your code or the compiler adds it. The actual mailCheck() method
looks like the following:
public void mailCheck()
{
System.out.println(“Mailing check to “ +
this.name + “\n” + this.address);
}
Notice that name and address are prefixed with
this
.
Classroom Q & A
Q:
The
this
reference seems a little confusing. Is it necessary?
A:
The
this
reference is one of those fundamental concepts of OOP
that tends to be confusing the first time you see it. To explain the
need for the
this
reference, I always try to emphasize the fact that
a field or method cannot be accessed without a reference. The
this
reference is the only way a method in a class can access the other
fields or methods of the class.
Q:
Why does the compiler add
this.
automatically?
A:
It is strictly for convenience. It would be fairly tedious (although
certainly feasible) to add
this.
every time it was required in a class.
In a large class, there could easily be hundreds of accesses to the
fields or methods of the class, each requiring the
this
reference.
For now, keep in mind that the
this
reference is implicitly being
used when a method in your class accesses a field of the class.
You can also use the
this
reference as an argument to a method, in which
an object passes a reference of itself to another object.